Daniel
Daniel

Reputation: 45

Parsing JSON in JAVA with GSON

I'm trying to parse a JSON file with GSON with the following structure:

{
  "state": 0,
  "orders": {
    "1": {
      "idOrder": "1564",
      "price": "7.99",
      },
    "3": {
      "idOrder": "4896",
      "price": "9.99",
      },
    "7": {
      "idOrder": "4896",
      "price": "10.99",
      }
  }
}

I made the classes as same structure (with setters and getters)

public class myJson {
private int error;
private Orders orders; }

public class Orders {
@SerializedName("1")
private _1 _1;}

public class _1 {
private String idOrder;
private String price;}

and in main I am using like this:

       Gson gson = new Gson();
       BufferedReader br = new BufferedReader (new FileReader("base.json"));
       Json jsonOffline = gson.fromJson(br, myJson.class);
       System.out.println("1 - Orderid: " + jsonOffline.getOrders().get1().getidOrder() );

*

And it works perfectly printing: "1 - Orderid: 1564"

*

And now my problem is that these numbers (1,3,7) in the JSON file are random and there may be many orders. Is there any way for me to indicate a range of numbers, for example, 1-1000, and in that case if the result is not null to do the same?

I mean, to avoid having to create 1000 classes like class _1

Upvotes: 1

Views: 84

Answers (2)

marme1ad
marme1ad

Reputation: 1383

Why not to do something like this:

public class MyJson {
    private int error;
    private Map<String, Order> orders;
    // getters and setters
}

With the Order defined so:

public class Order {
    private String idOrder;
    private String price;
    // getters and setters
}

And main method will look so:

public static void main(String[] args) throws FileNotFoundException {
    Gson gson = new Gson();
    BufferedReader br = new BufferedReader(new FileReader("base.json"));
    MyJson jsonOffline = gson.fromJson(br, MyJson.class);
    System.out.println("1 - Orderid: " + jsonOffline.getOrders().get("1").getIdOrder());
}

Upvotes: 0

Deividi Cavarzan
Deividi Cavarzan

Reputation: 10110

Change orders to a Map (HashMap)

private Map<String, Orders> orders;

And Orders to:

public class Orders {

    private String idOrder;
    private String price;

}

This should parse the Json as expected.

This question has a simular approach, but not using the class mapping in the example

Upvotes: 3

Related Questions