Gson响应解析与数组中的双引号

时间:2016-08-19 06:16:36

标签: android json gson

我的服务器发送如下数据。我正在使用Gson来解析这些数据。但它失败了以下例外:

{
   "users":[
      {
         "config":{
        "identifiers":{
           "id":"7"
        },
        "v_id":[
           "335",
           "Product User "
        ],
        "m_id":[
           "3530",
           "4744"
        ],
        "expand":{
           "chategory":[
              {
                 "identifiers":{
                    "id":"3"
                 },
                 "catConfig":{
                    "security":"Private"
                 }
              }
           ],
           "hobby":[
              {
                 "identifiers":{
                    "id":"200",
                    "d_id":[
                       "Playing \"Football\"",
                       "Music",
                       "Dancing",
                       "Browsing"
                    ]
                 },
                 "type":"Output"
              }
           ]
        }
     }
  }
   ]
}

异常

org.json.JSONException: Unterminated array at character 183 of "chategory":[{"identifiers":{"id":"3"},"catConfig":{"security":"Private"}}],"hobby":[{"identifiers":{"id":"200","d_id":["Playing"Football"","Music","Dancing","Browsing"]},"type":"Output"}]},
 at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
 at org.json.JSONTokener.readArray(JSONTokener.java:440)
 at org.json.JSONTokener.nextValue(JSONTokener.java:103)
 at org.json.JSONTokener.readObject(JSONTokener.java:385)
 at org.json.JSONTokener.nextValue(JSONTokener.java:100)
 at org.json.JSONTokener.readObject(JSONTokener.java:385)
 at org.json.JSONTokener.nextValue(JSONTokener.java:100)
 at org.json.JSONTokener.readArray(JSONTokener.java:430)
 at org.json.JSONTokener.nextValue(JSONTokener.java:103)
 at org.json.JSONTokener.readObject(JSONTokener.java:385)
 at org.json.JSONTokener.nextValue(JSONTokener.java:100)
 at org.json.JSONObject.<init>(JSONObject.java:156)
 at org.json.JSONObject.<init>(JSONObject.java:173)
 at honeywell.security.isom.customformatter.ExpansionJsonConverter.convertJsonStringIntoHashMap(ExpansionJsonConverter.java:80)
 at honeywell.security.isom.customformatter.ExpansionJsonConverter.read(ExpansionJsonConverter.java:64)
 at honeywell.security.isom.customformatter.ExpansionJsonConverter.read(ExpansionJsonConverter.java:22)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:118)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:253)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:118)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:253)
 at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
 at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
 at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:118)
 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:253)
 at com.google.gson.Gson.fromJson(Gson.java:981)
 at honeywell.security.isom.client.proxybase.BaseControllerProxy.deserializeTheResponse(BaseControllerProxy.java:554)
 at honeywell.security.isom.client.proxybase.BaseControllerProxy.excuteRequest(BaseControllerProxy.java:321)
 at honeywell.security.isom.client.proxybase.BaseControllerProxy.prepareDetailsToSendRequest(BaseControllerProxy.java:421)
 at honeywell.security.isom.client.proxybase.BaseControllerProxy.executeGETMethod(BaseControllerProxy.java:123)
 at honeywell.security.isom.client.proxycontroller.PeripheralsControllerProxy.getperipheralentitylist(PeripheralsControllerProxy.java:44)
 at com.mpcthreadlib.request.RequestISOM.getISOMRequest(RequestISOM.java:557)
 at com.mpcthreadlib.manage.RequestThread.executeRequest(RequestThread.java:102)
 at com.mpcthreadlib.manage.RequestThread.run(RequestThread.java:71)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

注意输入带有转义序列,其中Gson抱怨字符串没有它。此外,如果它是一个普通的JsonObject而不是JsonArray,它的工作正常。

可能是什么问题?

2 个答案:

答案 0 :(得分:0)

我提取了你的json部分

{"d_id":["Playing \"Football\"","Music","Dancing","Browsing"]}

我试图将你的json复制到Pojo类中并生成以下类

public class Bean {
    private String[] d_id;
    public String[] getD_id() {
        return d_id;
    }
    public void setD_id(String[] d_id) {
        this.d_id = d_id;
    }
    @Override
    public String toString() {
        return "ClassPojo [d_id = " + d_id + "]";
    }
}

RetrofitUtil

public class UtilRetrofit {
    public static String URL = "";
    private static ENDPointerListener sENDPointerListener;
    public static ENDPointerListener getENDPointerListener() {
        if (sENDPointerListener == null) {
            sENDPointerListener = new ENDPointerListener() {
                @Override
                public String getEndPoint() {
                    return URL;
                }
            };
        }
        return sENDPointerListener;
    }
    public static void setENDPointerListener(ENDPointerListener pENDPointerListener) {
        sENDPointerListener = pENDPointerListener;
    }
    public interface ENDPointerListener {
        String getEndPoint();
    }
    public static <T> T build(Class<T> t) {
        OkHttpClient okhttp = new OkHttpClient.Builder().addInterceptor(new StethoInterceptor()).build();
        Retrofit retrofit = new Retrofit.Builder().client(okhttp)
                .baseUrl(getENDPointerListener().getEndPoint())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                        .create()))
                .build();
        return retrofit.create(t);
    }
}

使用Retrofit和mock服务器来检索值

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        RestA rest = UtilRetrofit.build(RestA.class);
        Call<Bean> call = rest.geBean();
        call.enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                Bean data =response.body();
            }
            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
                Toast.makeText(getActivity(),t.toString(),Toast.LENGTH_SHORT).show();
            }
        });
    }

即使字符串中有双引号,我的结果也很好。你的bean类有什么问题吗?

@RunWith(AndroidJUnit4.class)
@SmallTest
public class RestATest {
    @Rule
    public ActivityTestRule<MainActivity> mMainActivityActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class, true, false);
    private MockWebServer mMock;
    @Before
    public void set() {
        mMock = new MockWebServer();
        try {
            mMock.play();
        } catch (IOException pE) {
            pE.printStackTrace();
        }
        //set the mock Server
        UtilRetrofit.URL = mMock.getUrl("/").toString();
    }
    @Test
    public void testRequest1() {
        String bodyStr = "{\"d_id\":[\n\"Playing \\\"Football\\\"\",\n\"Music\",\n\"Dancing\",\n\"Browsing\"\n]\n}";
        mMock.enqueue(new MockResponse().setResponseCode(200).setBody(bodyStr));
        mMainActivityActivityTestRule.launchActivity(null);
    }


}

答案 1 :(得分:0)

我尝试使用GSON默认的Deserializer并且工作正常。我没有任何例外。

private void parseJSON() {
    String json = "{\"users\":[{\"config\":{\"identifiers\":{\"id\":\"7\"},\"v_id\":[\"335\",\"Product User \"],\"m_id\":[\"3530\",\"4744\"],\"expand\":{\"chategory\":[{\"identifiers\":{\"id\":\"3\"},\"catConfig\":{\"security\":\"Private\"}}],\"hobby\":[{\"identifiers\":{\"id\":\"200\",\"d_id\":[\"Playing \\\"Football\\\"\",\"Music\",\"Dancing\",\"Browsing\"]},\"type\":\"Output\"}]}}}]}";

    Gson gson = new Gson();
    JSONResponse jsonResponse = gson.fromJson(json, JSONResponse.class);

    for (String s : jsonResponse.getUsers().get(0).getConfig().getExpand().getHobby().get(0).getIdentifiers().getDId()) {
        System.out.println(s);
    }

}

输出:

08-19 12:26:49.682 12405-12405/com.trial.mobileapps.gsontrial I/System.out: Playing "Football"
08-19 12:26:49.682 12405-12405/com.trial.mobileapps.gsontrial I/System.out: Music
08-19 12:26:49.682 12405-12405/com.trial.mobileapps.gsontrial I/System.out: Dancing
08-19 12:26:49.682 12405-12405/com.trial.mobileapps.gsontrial I/System.out: Browsing

GSON依赖

compile 'com.google.code.gson:gson:2.7'