[英]Convert serialized JSON string to JSON object in java
我有 Json 字符串 Object 如下。
"{\"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 object。
我已經試過了,
JSONObject jsonObj = new JSONObject(response);
我收到一個error
消息,
org.json.JSONException: A JSONObject text must begin with '{'
"{\"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 object 以{
字符開頭。 根據對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);
}
}
因此,如果您收到JSONException
則輸入不是 Java String
文字。
1 - 我不會說它是正確的。 AppData
屬性的值是一個字符串,而不是 JSON object。 但該字符串是 JSON 序列化。 這在技術上是有效的,但它是一個糟糕的設計選擇。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.