简体   繁体   中英

Parse every element of JSON to Array in Java

JAVA

I want to parse every element of JSON file (using gson will be the best) to Array. I searched for two days and I still can't figure out how to do it correctly. My JSON file looks like this:

{
  "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. 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:

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.


edit

If you want the class you are currently using you need a JSON string of this form:

[
  {
    "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 ):

[
  {
    "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.

With GSON

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. But you can iterate each element with GSON using JsonObject.entrySet

First, parse the JSON and get the object:

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() .

Note this can be improved using a Stream but to keep it family friendly ;) I will keep that loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM