gpt4 book ai didi

java - 如何使用GSON将json对象数组解析为JAVA二维数组?

转载 作者:行者123 更新时间:2023-11-30 10:41:54 27 4
gpt4 key购买 nike

我有这样的 JSON 字符串:

[{
"id": 3,
"city": "Ilmenau",
"floor": null,
"housenumber": "35",
"streetname": "Blumenstraße",
"zip": "98693"
}, {
"id": 4,
"city": "Berlin",
"floor": null,
"housenumber": "54",
"streetname": "Bogdansplatz",
"zip": "194354"
}]

我需要将其解析为如下所示的二维数组: enter image description here我怎样才能使用 GSON java 库?现在我只写了这段代码,它返回一个列表:

String s=getJson("SELECT * FROM address;");

JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(s);
JsonArray jsonArr = jo.getAsJsonArray("array");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());

但是上面的代码只适用于数组的 JSON 对象,不适用于我上面显示的字符串。

最佳答案

请您尝试以下操作并查看结果:

// String 's' holds the JSON 

JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(s);

// this object is used to get the keys
JsonObject firstJsonObject = jsonArray.get(0).getAsJsonObject();
Set<java.util.Map.Entry<String, JsonElement>> entrySet = firstJsonObject.entrySet();

// declare two dimensional array
Object[][] array = new Object[entrySet.size()][jsonArray.size() + 1];

// the first column of the two-dimensional array is populated
Iterator<java.util.Map.Entry<String, JsonElement>> itr = entrySet.iterator();
for (int i = 0; itr.hasNext(); i++) {
array[i][0] = itr.next().getKey();
}

// the rest of the columns are populated
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
for (int j = 0; j < array.length; j++) {
String key = array[j][0].toString();
JsonElement value = obj.get(key);
array[j][i + 1] = value instanceof JsonNull ? null : value.getAsString();
}

}
// now the two dimensional array is fully populated

关于java - 如何使用GSON将json对象数组解析为JAVA二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348719/

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