这是什么错误?我该怎么解决这个问题?我的应用正在运行,但无法加载数据.这是我的错误:使用JsonReader.setLenient(true)在第1行第1列路径接受格式错误的JSON$

这是我的片段:

public class news extends Fragment {


private RecyclerView recyclerView;
private ArrayList<Deatails> data;
private DataAdapter adapter;
private View myFragmentView;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    myFragmentView = inflater.inflate(R.layout.news, container, false);
    initViews();
    return myFragmentView;

}


private void initViews() {
    recyclerView = (RecyclerView) myFragmentView.findViewById(R.id.card_recycler_view);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    data = new ArrayList<Deatails>();
    adapter = new DataAdapter(getActivity(), data);
    recyclerView.setAdapter(adapter);

    new Thread()
    {
        public void run()
        {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadJSON();
                }
            });

        }
    }
    .start();
}

private void loadJSON() {
    if (isNetworkConnected()){

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(15, TimeUnit.SECONDS)
                .build();

        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.memaraneha.ir/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.show();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
                progressDialog.dismiss();
                JSONResponse jsonResponse = response.body();
                data.addAll(Arrays.asList(jsonResponse.getAndroid()));
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                progressDialog.dismiss();
                Log.d("Error", t.getMessage());
            }
        });
    }
    else {
        Toast.makeText(getActivity().getApplicationContext(), "Internet is disconnected", Toast.LENGTH_LONG).show();}
}
private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null) {
        // There are no active networks.
        return false;
    } else
        return true;
}
}

RequestInterface :

public interface RequestInterface {

@GET("Erfan/news.php")
Call<JSONResponse> getJSON();
}

a

更新(阅读下面的文字,找出你的问题)

  • most of the time, this error isn't about your json but it could be a incorrect http request such as a missing or a incorrect header, first check your request with postman to verify the servers response and servers response headers. if nothing is wrong then the error mostly came from your programmed http request, also it could because the servers response is not json (in some cases response could be html).

推荐答案

这是一个众所周知的问题,根据this个答案,您可以添加setLenient个:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

现在,如果你把这个加到你的retrofit上,它会给你另一个错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

这是您可以找到答案here的另一个众所周知的错误(此错误意味着您的服务器响应的格式不正确);因此,请更改服务器响应以返回以下内容:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

为了更好地理解,将你的回答与Github api进行比较.

Suggestion:要想知道你的request/response是怎么回事,在retrofit中加HttpLoggingInterceptor.

根据this个答案,你的ServiceHelper个答案是:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

另外,不要忘记添加:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Json相关问答推荐

为什么terraform不缩小这个策略JSON?'

最新版本的Deneb在数据溢出时不支持滚动

褐煤面积图中的分选问题

如何使用模式注册中心创建从主题中取消本地化的ks qlDB表?

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

在linux控制台中解析json字符串的最简单方法是什么?

Spark-SQL中的from_unixtime函数未能给出正确的输出

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

将请求中的数据推送到数组中

JSON 模式实际用于什么目的?

当值包含ansible中的字符串时解析json值

如何用 Xidel 正确读取这个 JSON 文件?

解析包含换行符的 JSON

没有很多类的 GSON 解析

C#扁平化json struct

alert Json 对象

区分字符串和列表的 Pythonic 方式是什么?

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

Retrofit2.0 得到 MalformedJsonException 而 json 似乎正确?

在 HTML 数据属性上添加 JSON 是不是很糟糕?