[英]Parse every element of JSON to Array in Java
JAVA JAVA
I want to parse every element of JSON file (using gson will be the best) to Array. 我想将JSON文件的每个元素(最好使用gson)解析为Array。 I searched for two days and I still can't figure out how to do it correctly. 我搜寻了两天,但仍然找不到正确的方法。 My JSON file looks like this: 我的JSON文件如下所示:
{
"spawn1": {
"x": 336.4962312645427,
"y": 81.0,
"z": -259.029426052796
},
"spawn2": {
"x": 341.11558917719424,
"y": 80.0,
"z": -246.07415114625
}
}
There will be more and more elements with different names. 将会有越来越多的具有不同名称的元素。 What I need is to take all the elements like x, y, z and create an object using it and place it to the array. 我需要的是像x,y,z这样的所有元素并使用它创建一个对象并将其放置到数组中。 Class for this object looks like this: 该对象的类如下所示:
public class Chest {
private double x, y, z;
public Chest(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
With the class you are currently using it is not going to work. 对于您当前正在使用的课程,它将无法正常工作。
Your JSON String currently wants 2 classes that look like this: 您的JSON字符串当前需要2个类似以下的类:
public class ClassOne
{
ClassTwo spawn1;
ClassTwo spawn2;
}
public class ClassTwo
{
double x;
double y;
double z;
}
So you need to either change your JSON or your class structure. 因此,您需要更改JSON或类结构。
edit 编辑
If you want the class you are currently using you need a JSON string of this form: 如果要使用当前正在使用的类,则需要以下形式的JSON字符串:
[
{
"x": 1.0,
"y": 2.0,
"z": 3.0
},
{
"x": 4.0,
"y": 5.0,
"z": 6.0
}
]
If you want to maintain your spawn1
and spawn2
field add a String
field to your class and use a JSON String like this (here the field has the name name
): 如果要维护您的spawn1
和spawn2
字段,请在您的类中添加一个String
字段,并使用如下所示的JSON String(此处的字段名称为name
):
[
{
"name": "spawn1",
"x": 1.0,
"y": 2.0,
"z": 3.0
},
{
"name": "spawn2",
"x": 4.0,
"y": 5.0,
"z": 6.0
}
]
Both of these return an Chest[]
when you convert them from JSON. 从JSON转换它们时,它们都返回Chest[]
。
Using the JSON you have is a bit tricky since you said the number of Object can change but those are not in an array. 使用JSON有点棘手,因为您说过对象的数量可以更改,但是这些不在数组中。 But you can iterate each element with GSON using JsonObject.entrySet
但是您可以使用JsonObject.entrySet
使用GSON迭代每个元素
First, parse the JSON and get the object: 首先,解析JSON并获取对象:
JsonObject json = JsonParser.parse(jsonToParse).getAsJsonObject();
Then you iterate the elements : 然后,您迭代元素:
List<Chest> list = new ArrayList<>();
for(Entry<String, JsonElement> e : json.entrySet()){
//read the json you can find in `e.getValue()`
JsonObject o = e.getValue().getAsJsonObject();
double x = o.getAsJsonPrimitive("x").getAsDouble();
...
//create the instance `Chest` with those `double` and insert into a `List<Chest>`
list.add(new Chest(x,y,z));
}
If you want to retrieve the name to, it is in the entry key : e.getKey()
. 如果要检索名称,则在输入键中: e.getKey()
。
Note this can be improved using a Stream
but to keep it family friendly ;) I will keep that loop. 请注意,可以使用Stream
进行改进,但要使其与家人保持友好;)我将保留该循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.