Android - 奇怪的EscapeUtil.unescapeString崩溃

时间:2017-03-31 22:32:30

标签: java android json unescapestring

我从应用服务器接收JSON字符串时遇到崩溃。我们认为,当某个条目引用"引用"时,会添加额外转义

double escapes??

在android中,我如何确定是否收到这样的字符串,如何从Android端修复它?

这是我们当前的响应字符串处理:

public String processResponseString(String responseString) {
    if (responseString.startsWith("\"")) {
        responseString = responseString.substring(1, responseString.length());
    }
    if (responseString.endsWith("\"")) {
        responseString = responseString.substring(0, responseString.length() - 1);
    }
    responseString = EscapeUtil.unescapeString(responseString);
    return responseString;
}

此外,崩溃后logcat不包含整个json字符串,因此我看不到导致崩溃的实际字符串。

异常

 java.lang.ClassCastException: com.optiisolutions.housekeeping.model.OptiiAPI.OptiiError cannot be cast to java.util.Map
 at com.optiisolutions.housekeeping.network.OptiiHTTPClientRetroFit$2.success(OptiiHTTPClientRetroFit.java:186)
 at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)

OptiiHTTPClientRetroFit.java:186

optiiClient.postRequest(event.getRequest(), new Callback<Map<String, Object>>() {
    @Override
     public void success(Map<String, Object> stringObjectMap, Response response) {
         Log.d(TAG, "Successful response: " + stringObjectMap.toString());
          String result = (String) stringObjectMap.get(OPTII_RESULT_TYPE);
          String json = gson.toJson(stringObjectMap, Map.class);

2 个答案:

答案 0 :(得分:3)

我认为您需要使用JSONValue将Map解析为JSON,如下面的代码。

optiiClient.postRequest(event.getRequest(), new Callback<Map<String, Object>>() {
    @Override
     public void success(Map<String, Object> stringObjectMap, Response response) {
         Log.d(TAG, "Successful response: " + stringObjectMap.toString());
        // For JsonValue you need to add one jar file .
         String json= JSONValue.toJSONString(stringObjectMap);
         Log.d(TAG, "Successful json: " + json);
}

需要在javax.json-1.0.2.jar依赖项

中添加jar gradle
dependencies {
    compile files('libs/javax.json-1.0.2.jar')
}

下载javax.json-1.0.2.jar从以下链接下载:

http://www.java2s.com/Code/Jar/j/Downloadjavaxjson102jar.htm

答案 1 :(得分:0)

我试图复制你的字符串。我假设你想保留报价。我可以用这个简单的算法解决它,希望它适合你:

    public static String process(String s){
       String sep = "\\\\";
       String[] arr = s.split(sep);
       StringBuilder sb = new StringBuilder();

       for(String str : arr){
          sb.append(str);
       }

       return sb.toString();
    }