[英]How do I remove backslashes before quotes from a JSONObject string?
我有一個由類動態創建的字符串(記錄)列表。 每個記錄可以具有不同的密鑰(例如favorite_pizza
上第一, favorite_candy
上秒)。
// Note: These records are dynamically created and not stored
// in this way. This is simply for display purposes.
List<String> records =
Arrays.asList(
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}");
然后將記錄列表傳遞給單獨的 HTTP 請求類。
public Response addRecords(List<String> records) {
...
}
在 HTTP 請求服務中,我想構建一個 JSON 請求正文:
{
"records": [
{
"name": "Bob",
"age": 40,
"favorite_pizza": "Cheese"
},
{
"name": "Jill",
"age": 22,
"favorite_candy": "Swedish Fish"
}
]
}
我正在使用org.json.JSONObject添加records
鍵並創建請求正文:
JSONObject body = new JSONObject();
// Add the "records" key
body.put("records", records);
// Create the request body
body.toString();
當我在 IntelliJ 中運行我的 junit 測試時,請求正文在每個引號之前包含一個反斜杠:
org.junit.ComparisonFailure:
Expected :"{"records":["{"name":"Bob","age":40,"favorite_pizza":"Cheese"}","{"name":"Jill","age":22,"favorite_candy":"Swedish Fish"}"]}"
Actual :"{"records":["{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}","{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}"]}"
當我發出請求時,它失敗了,因為正文格式不正確:
{
"records": [
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}"
]
}
您正在創建一個字符串列表,這不是您想要的。
您應該創建一個對象列表(地圖)
Map<String, Object> m1 = new LinkedHashMap<>();
m1.put("name", "Bob");
m1.put("age", 40);
m1.put("favorite_pizza", "Cheese");
LinkedHashMap<String, Object> m2 = new LinkedHashMap<>();
m2.put("name", "Jill");
m2.put("age", 22);
m2.put("favorite_candy", "Swedish Fish");
List<LinkedHashMap<String, Object>> records = Arrays.asList(m1,m2);
JSONObject body = new JSONObject();
// Add the "records" key
body.put("records", records);
這是一個很常見的錯誤(似乎),嘗試序列化格式為 json 對象的字符串與傳遞對象本身是一樣的。
更新:
或者,如果您有一個 json 序列化對象列表,那么...
List<String> recordSource =
Arrays.asList(
"{\"name\":\"Bob\",\"age\":40,\"favorite_pizza\":\"Cheese\"}",
"{\"name\":\"Jill\",\"age\":22,\"favorite_candy\":\"Swedish Fish\"}");
List<JSONObject> records =
recordSource.stream().map(JSONObject::new).collect(Collectors.toList());
JSONObject body = new JSONObject();
// Add the "records" key
body.put("records", records);
System.out.println(body.toString());
如果您的記錄字符串已經是有效的 json,您可以
迭代它們,一次將它們轉換為JSONObject
(參見此處),然后將結果添加到JSONArray
,您可以根據需要對其進行操作。
完全手動創建數組,因為它只是方括號內的逗號分隔記錄字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.