我有一个 JSON 格式的字符串
String str = "{\"innerkey1\":\"innervalue1\",
\"innerkey2\":\"innervalue2\",\"innerkey1\":\"innervalue3\"}";
当我试图从这个字符串创建一个对象时
try {
JSONObject obj = new JSONObject(str);
} catch(Exception e) {
e.printStackTrace();
}
我遇到了一个错误
org.json.JSONException: Duplicate key "innerkey1"
有没有什么方法可以通过忽略字符串中的最后一个键来创建 JSONObject?
最佳答案
您可以使用 objectMapper 来跳过这个错误
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"test\", \"name\":\"new test\"}";
Map<String, Object> map = new HashMap<String, Object>();
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
现在您可以轻松地将 map 转换为 JSONObject
new JSONObject(map);
关于java - 忽略 JSONObject 中的重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876328/