gpt4 book ai didi

java - 将 JSON 对象转换为具有键值对的平面对象

转载 作者:行者123 更新时间:2023-11-29 09:27:40 24 4
gpt4 key购买 nike

我得到一个 JSON 对象,如下所示:

{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
{
"items": [{
"id": "1"
}]
}
}

我想将其表示为平面 map ,但我想将项目数组表示为列表。

我的输出应该是这样的:

{
"id": "1",
"name":"Hw",
"price":"10",
"items": ["1"]
}

任何人都可以建议我如何实现这一目标吗?我试过这种方法:

How to deserialize JSON into flat, Map-like structure?

上述尝试链接的输出:

{
"id": "1",
"name":"Hw",
"price.value":"10",
"items[0].id": "1"
}

但它将数组值表示为 array[0], array[1] 我不需要。我需要这个数组作为列表。

最佳答案

您提供的 JSON 无效。我假设它是:

{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [{
"id": "1"
}]
}

对于您的要求,没有通用的解决方案。但是对于这个特定的 JSON,这会做(使用 json-simple ):

@SuppressWarnings("unchecked")
public Map<String, String> transform(String inputJSON) throws ParseException {
Map<String, String> result = new LinkedHashMap<>();
JSONObject inputJSONObj = (JSONObject) new JSONParser().parse(inputJSON);
String id = inputJSONObj.getOrDefault("id", "").toString();
String name = inputJSONObj.getOrDefault("name", "").toString();
String price = ((JSONObject) inputJSONObj.getOrDefault("price", new JSONObject())).getOrDefault("value", "")
.toString();
JSONArray itemsArray = (JSONArray) inputJSONObj.getOrDefault("items", new JSONArray());
int n = itemsArray.size();
String[] itemIDs = new String[n];
for (int i = 0; i < n; i++) {
JSONObject itemObj = (JSONObject) itemsArray.get(i);
String itemId = itemObj.getOrDefault("id", "").toString();
itemIDs[i] = itemId;
}
result.put("id", id);
result.put("name", name);
result.put("price", price);
result.put("items", Arrays.toString(itemIDs));
return result;
}

关于java - 将 JSON 对象转换为具有键值对的平面对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45378953/

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