我有如下的Json String对象。
"{\"SuccessData\":\"Data fetched successfully\",\"ErrorData\":\"\",\"AppData\":\"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"}"
我想使用Java将此字符串转换为JSON对象。
我已经尝试过
JSONObject jsonObj = new JSONObject(response);
我听到error
的话,
org.json.JSONException: A JSONObject text must begin with '{'
答案 0 :(得分:0)
"{\"SuccessData\": \"Data fetched successfully\",
\"ErrorData\": \"\",
\"AppData\": \"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"
}"
这里的真正问题是此输入无效的JSON。
让我们假设这些是您在响应中得到的确切字符;即第一个字符是双引号。但是有效的JSON对象以{
字符开头。根据严格阅读https://json.org上的语法图,甚至不允许使用空格。
但是,如果那实际上是代表JSON的Java String
文字怎么办?
在这种情况下,JSON有效 1 。而且,您的JSON代码是正确的。当我编译并运行它时,它可以正常工作……而不会引发异常。
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String response = "{\"SuccessData\":\"Data fetched successfully\",\"ErrorData\":\"\",\"AppData\":\"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"}";
JSONObject jsonObj = new JSONObject(response);
}
}
Ergo,如果您得到JSONException
,则输入的不是Java String
文字。
1-我不会说这是正确的。 AppData
属性的值是不是JSON对象的字符串。但是该字符串是JSON序列化。从技术上讲这是有效的,但这是一个糟糕的设计选择。
答案 1 :(得分:0)
I tried with the following solution and it is working,
import com.fasterxml.jackson.databind.ObjectMapper;
private JSONObject deserializeResponse(String response) {
logger.info("Parsing Serialized response object to JSON object");
JSONObject responseJson = new JSONObject();
ObjectMapper mapper = new ObjectMapper();
try {
responseJson = mapper.readValue(response.toString(),
JSONObject.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseJson;
}