当前位置: 首页 > 知识库问答 >
问题:

使用JsonReader。setLenient(true)在第1行第1列路径接受格式错误的JSON$

荆钱明
2023-03-14

这个错误是什么?我怎样才能解决这个问题?我的应用程序正在运行,但无法加载数据。这是我的错误:使用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;
}
}

请求接口:

public interface RequestInterface {

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

  • 总是这个错误不是关于你的json,它可能来自你的错误请求,为了更好地处理,首先在邮递员中检查你的请求,如果你得到了响应,然后将你的json响应与你的模型进行比较,如果没有错误,那么这个错误来自你的错误请求,也可能发生在您的响应不是josn(在某些情况下,响应可能是html)

共有3个答案

孙自怡
2023-03-14

使用Moshi:

在构建改装服务时添加。对你最重要的工厂宽容一点。你不需要ScalarsConverter。应该是这样的:

return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .build()
                .create(UserService::class.java)
郭兴文
2023-03-14

当响应contenttype不是application/json时,也会出现此问题。在我的例子中,响应内容类型是text/html,我面临这个问题。我把它改成了application/json,然后它就工作了。

顾乐池
2023-03-14

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

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

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

现在,如果将此添加到改装中,则会出现另一个错误:

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

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

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

为了更好地理解,请将您的响应与Github api进行比较。

建议:要了解您的请求/响应发生了什么请在您的改装中添加HttpLoggingInterceptor

基于此答案,您的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'
 类似资料: