【问题标题】:Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON
【发布时间】:2017-02-16 13:05:59
【问题描述】:

这是什么错误?我怎样才能解决这个问题?我的应用程序正在运行,但无法加载数据。这是我的错误:使用 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 无关,但可能是 不正确的 http 请求,例如缺少或不正确的标头,首先使用邮递员检查您的请求以验证服务器响应和服务器响应标头。如果没有问题,则错误主要来自您编写的 http 请求,也可能是因为服务器响应不是 json(在某些情况下响应可能是 html)。

【问题讨论】:

  • 请显示您从response.body()收到的输出
  • @cricket_007 我编辑我的问题并显示我的结果
  • 我没有要求图片。我让你打印出可能从服务器返回的值。
  • 如何在 Java 中打印一个值? System.out.println,是吗?在 Android 中,您可以使用 Log 类,但这并不重要。在JSONResponse jsonResponse = response.body(); 或其附近,您没有获得数据或发生错误。我不知道如何解决您的错误,因为它可能与网络有关。您应该能够自行检查该值。
  • 我也不是专业人士,我只是想教你如何调试任何 Java 应用程序,而不是真正的 Android 特定

标签: android json gson retrofit


【解决方案1】:

这是一个众所周知的问题,基于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 进行比较。

建议:要了解您的request/response 发生了什么,请在您的改造中添加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'

【讨论】:

  • 我编辑我的问题外观。但给出相同的错误:使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON。还添加有问题的错误图片
  • @erfan 查看已编辑的答案;问题是因为您来自服务器的响应是 Not 正确的;删除“属性名称周围的问题将得到修复。
  • { android:[ { ver:"1.5", name:"Cupcace", api:"Api Level 3" , pic:"pic2.jpg"} ] } 这是我的 json 和你的一模一样示例和仍然相同的错误:'(
  • {"android": [ {"ver":"1.5","name":"Cupcace","api":"level3","pic":"bane.jpg"}] } , 用这种方式修复
  • 使用它,它会立即告诉你为什么你的 json 是错误的jsonlint.com
【解决方案2】:

当响应内容类型不是application/json 时,也会出现此问题。在我的情况下,响应内容类型是text/html,我遇到了这个问题。我把它改成application/json 然后它工作了。

【讨论】:

    【解决方案3】:

    使用 Moshi:

    在构建改造服务时,将 .asLenient() 添加到 MoshiConverterFactory。您不需要 ScalarsConverter。它应该看起来像这样:

    return Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(ENDPOINT)
                    .addConverterFactory(MoshiConverterFactory.create().asLenient())
                    .build()
                    .create(UserService::class.java)
    

    【讨论】:

      【解决方案4】:

      对返回类型的理解有误 只需添加 Header 即可解决您的问题

      @Headers("Content-Type: application/json")
      

      【讨论】:

      • 在我的情况下,我通过添加解决了它:@Headers("Accept: application/json")
      【解决方案5】:

      我和https://stackoverflow.com/a/57245058/8968137 有同样的问题,在修复 google-services.json 后都解决了

      【讨论】:

        【解决方案6】:

        我遇到了这个问题,我做了研究,没有得到任何东西,所以我尝试了,最后,我知道了这个问题的原因。 API 上的问题,确保你有一个好的变量名 我使用了 $start_date 并且它导致了问题,所以我尝试了 $startdate 并且它有效!

        还要确保发送所有在 API 上声明的参数,例如, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];

        你必须从改造中传递这两个变量。

        如果您在 SQL 语句中使用日期,请尝试将其放入 '' 比如'2017-07-24'

        希望对你有帮助。

        【讨论】:

          【解决方案7】:

          就我而言;解决我的问题的是.....

          你可能有这样的 json,没有 " double 引号的键....

          { 姓名:“测试”,电话:“2324234”}

          所以尝试任何在线 Json 验证器以确保您的语法正确...

          Json Validator Online

          【讨论】:

            【解决方案8】:

            发现当您没有输出正确的 JSON 对象时会发生这种情况后,我很容易解决了这个问题,我只是在我的 php api 中使用了echo json_encode($arrayName); 而不是print_r($arrayName);

            每种编程语言或至少大多数编程语言都应该有自己的 json_encode()json_decode() 函数版本。

            【讨论】:

            • 非常感谢!它帮助并节省了我的时间!
            【解决方案9】:

            在我的情况下,我忘记将 @Headers("Accept: application/json") 添加到 Retrofit 并在 http 页面上重定向,在 body razer json 中使用 html

            【讨论】:

              【解决方案10】:

              我突然开始出现这个问题,所以我确信,可能还有其他原因。在深入挖掘时,这是一个简单的问题,我在 Retrofit 的 BaseUrl 中使用了 http 而不是 https。所以将其更改为https 为我解决了这个问题。

              【讨论】:

                【解决方案11】:

                另外值得检查的是你的接口方法的返回类型是否有任何错误。我可以通过像Call&lt;Call&lt;ResponseBody&gt;&gt;这样的意外返回类型来重现这个问题

                【讨论】:

                • 当我使用ResponseBody 时,它解决了这个问题。
                猜你喜欢
                • 2017-06-03
                • 2018-08-25
                • 1970-01-01
                • 1970-01-01
                • 2018-06-24
                • 1970-01-01
                • 2018-05-17
                • 2020-02-08
                • 1970-01-01
                相关资源
                最近更新 更多