在不知道键的情况下解析json [英] Parse json without knowning the keys
问题描述
我试图在不知道键和json格式的结构的情况下用java解析json并将该数据保存到哈希图中
i am trying to parse json in java without knowing the keys and the structure of json format and save that data into the hashmap
我将如何循环遍历整个json格式并将键和值存储到哈希图中
how would i cycle through the whole json format and store key and value into the hashmap
{"id" : 12345, "value" : "123", "person" : "1"}
像本例一样,所有键都是jsonobject,它们都不是json数组
like in this example all the keys would be jsonobject none of them will be json array
还有其他一些库,例如杰克逊,我不想使用任何第三方库
There is some other library like jackson i don't want to use any third party library
推荐答案
这只是一个示例. 对于像
This is Just an Example. For a JSON Like
{
"status": "OK",
"search_result": [
{
"product": "abc",
"id": "1132",
"question_mark": {
"141": {
"count": "141",
"more_description": "this is abc",
"seq": "2"
},
"8911": {
"count": "8911",
"more_desc": "this is cup",
"seq": "1"
}
},
"name": "some name",
"description": "This is some product"
},
{
"product": "XYZ",
"id": "1129",
"question_mark": {
"379": {
"count": "379",
"more_desc": "this is xyz",
"seq": "5"
},
"845": {
"count": "845",
"more_desc": "this is table",
"seq": "6"
},
"12383": {
"count": "12383",
"more_desc": "Jumbo",
"seq": "4"
},
"257258": {
"count": "257258",
"more_desc": "large",
"seq": "1"
}
},
"name": "some other name",
"description": "this is some other product"
}
]
}
使用JSONObject keys()获取密钥,然后迭代每个密钥以获取动态值.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
大致代码如下:
// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}
也可以尝试使用此代码
public void parse(String json) {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key:"field.getKey() + "\tValue:" + field.getValue());
}
}
也请看一下此链接
https://github.com/alibaba/fastjson
这篇关于在不知道键的情况下解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!