【问题标题】:Getting JsonSyntaxException in Android retrofit response?在 Android 改造响应中获取 JsonSyntaxException?
【发布时间】:2015-10-19 06:55:47
【问题描述】:

相关Question

Json 的响应是 New line delimiter Json

{"type":"data","id":"xyz"}
{"type":"value","id":"xcf"}
....
....

我正在使用Retrofit 提出请求:

public void getWarehouse(){

 //Generation of  RestAdapter
 RestAdapter adapter = new  RestAdapter.Builder ()
            .setEndpoint(URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setLog(new AndroidLog("= NETWORK ="))
            .build();

 //Making request to API
 adapter.create(WarehouseAPI.class).getWarehouse()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<Response>() {
         @Override
         public void onCompleted() {
             Log.d(this.getClass().getName(), "OnCompleted ()");
         }

         @Override
         public void onError(Throwable e) {
             Log.d(this.getClass().getName(), "Error:"  + e.toString());
         }

         @Override
         public void onNext(Response response) {
         System.out.println("test");

         }


       });

}

我可以在Android Studio console 中看到回复,但出现以下错误:

Error:retrofit.RetrofitError: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2 path $

错误的可能性

  • 响应在 NdJson 中,但无法正确解析

问题

  • 如何正确解析?

【问题讨论】:

  • 您是否尝试将其作为数组读取?你的回复应该用 [] 包裹吗?
  • @trevor-e 实际上是NdJson。所以没有JsonArrayJsonObject 将在这里工作。请看一下这个问题:stackoverflow.com/questions/15121584/…(如果我没记错的话)
  • 我明白了。我相信你需要指定一个客户转换器来改造来处理这个问题,可能使用自定义 Gson 对象。
  • 我在retrofit 方面没有足够的经验,但是否有可能得到任何形式的回复。我的意思是我可以通过上面的代码从请求中获得响应(因为我可以在我的工作室控制台中看到通过改造而来的数据)

标签: java android json gson retrofit


【解决方案1】:

正如@trevor-e 提到的,您必须实现一个自定义转换器来处理 ndjson 格式。查看下面的链接以获取开始指南:

Retrofit — Define a Custom Response Converter

还可以查看来自 How can I return String or JSONObject from asynchronous callback using Retrofit? 的 StringConverter

您可能会将响应转换为常规字符串,然后将每一行解析为 JSON 对象并从那里继续。

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 2018-06-11
    • 2017-11-03
    • 2023-03-14
    • 2016-10-02
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多