我正在尝试将 json 字符串解码为 Map。
我知道有很多这样的问题,但我需要非常具体的格式。例如,我有 json 字符串:
{
"map": {
"a": "b",
"c": "d",
},
"map2": {
"aa": "bb",
"cc": "dd",
},
"something": "a",
"something2": "b"
}
我需要得到如下结果:
"map.a" => "b"
"map.c" => "d"
"map2.aa" => "bb"
"map2.cc" => "dd"
"something" => "a"
"something2" => "b"
我确定按键不会包含任何点。我查看了一些 JSON 库,但我不需要那么多函数,只需解码并存储在 Java 映射中即可。如果没有简单的方法,我会为此编写自己的算法,我希望它不会那么难......
感谢您的帮助。
最佳答案
我使用了org.codehaus.jackson
。执行以下操作:
HashMap<String, Object> content = null;
HashMap<String, String> result = new HashMap<String, String>();
try {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
content = mapper.readValue(jsonString, typeRef);
} catch (Exception ex) {
System.out.println("Exception : " + ex);
}
// now content has everything inside
for(String s : content.keySet()){
Object obj = content.get(s);
if(obj instanceof String){
result.put(s, (String)obj);
} else {
HashMap<String,String> hm = (HashMap<String,String>)obj;
for(String s2: hm.keySet()){
result.put(s+"."+s2, hm.get(s2));
}
}
}
编辑:已测试且正在运行
关于Java 解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15767442/