我正在使用下面的代码。得到这个输出。
输出
标题:{"id" : 12345, "value" : "123", "person" : "1"}
CDD:{"CDDid" : 3456 }
但我需要的输出如下:
标题ID 12345
标题值123
标题人1
CDD CDDid 3456
import org.json.JSONException;
import org.json.JSONObject;
public class Test{
private static HashMap<String, Object> getHashMapFromJson(String json) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject(json);
for (Iterator<String> it = jsonObject.keys(); it.hasNext();) {
String key = it.next();
map.put(key, jsonObject.get(key));
}
return map;
}
public static void main(String[] args ){
String json = " { \"Header\" : {\"id\" : 12345, \"value\" : \"123\", \"person\" : \"1\"} ,\"CDD\" : {\"CDDid\" : 3456 }}";
try {
HashMap<String, Object> map = getHashMapFromJson(json);
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
} catch (JSONException e) {
System.out.println("JsonTest" + "Failed parsing " + json + e);
}
}
}
答案 0 :(得分:1)
这是我的解决方案,我希望在getHashMapFromJson
方法中已经正确使用。
toMap方法是简化版from this answer,如果你的json更复杂,你可能想要从该答案和toMap
方法中实现完整的toList
方法。
private static HashMap<String, Object> getHashMapFromJson(String json) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject(json);
for (Iterator<String> it = jsonObject.keys(); it.hasNext();) {
String key = it.next();
JSONObject value = jsonObject.getJSONObject(key);
Map<String, Object> valueMap = toMap((JSONObject) value);
valueMap.forEach((k,v) -> map.put(key + " " + k, v));
}
return map;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
map.put(key, value);
}
return map;
}
答案 1 :(得分:0)
String headerId = json.getJSONObject("Header").getString("id");
String headerValue = json.getJSONObject("Header").getString("value");
String headerperson = json.getJSONObject("Header").getString("person");
String CDDid = json.getJSONObject("CDD").getString("CDDid ");
这种方式可以检索json数据