gpt4 book ai didi

java - 在不知道 key 的情况下解析 json

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:55 31 4
gpt4 key购买 nike

我正在尝试在不知道 json 格式的键和结构的情况下在 java 中解析 json,并将该数据保存到 hashmap 中

我将如何遍历整个 json 格式并将键和值存储到 hashmap 中

 {"id" : 12345, "value" : "123", "person" : "1"}

就像在这个例子中,所有的键都是jsonobject,没有一个是json数组

还有一些其他的库,比如 jackson,我不想使用任何第三方库

最佳答案

这只是一个例子。对于像

这样的 JSON
{
"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() 获取键,然后迭代每个键以获取动态值。

代码大致如下:

// 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

关于java - 在不知道 key 的情况下解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25680929/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com