我正在尝试使用 GSON 解析 JSON,我想我已经掌握了它的窍门。我遇到的问题是它似乎在对象名称之后停止解析。
public static void main(String[] args) throws Exception {
Gson gson=new Gson();
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,String> map=new HashMap<String,String>();
map=(Map<String,String>) gson.fromJson(json, map.getClass());
System.out.println(map.keySet());
}
工作正常并输出:
[k1,k2]
我可以使用这些键来获取正确的值,这就是我想要做的。
如果我对来自 json.org 的 JSON 对象使用相同的代码
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
我得到的唯一输出是
[词汇表]
我觉得我明显遗漏了一些东西,有人可以帮我指出正确的方向吗?
谢谢。
最佳答案
JSON 对象(包含 "glossary"
)比 Map
更复杂。可转换为 Java 的 JSON 对象示例 Map<String, String>
将是:
{"key1": "value1", "key2": "value2", "key3": "value3"}
However, in the example JSON object, there is a string key whose value is JSON object, not a String
, which does not convert to Map<String, String>
:
{"key": {"anotherKey": "some value"}}
There is an example from the Gson homepage here. To properly de-serialize your example, you will have to use a combination of JsonParser
and Gson
. For example,
String jsonObject = "your example";
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(jsonObject).getAsJsonObject();
JsonObject glossary = obj.get("glossary");
等等...
关于java - GSON 只解析对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535013/