0

Is there any way to mapping nested json object into single Java class? for example, I have this json string:

{
  "order_id": 104,
  "order_details" : [
    {
      "name": "Product#1",
      "price": {
        "usd": 12.95
      }
    }
  ]
}

I want to map with this class:

public class Order{
   Int id; // rename
   String name; //map with order_details.name
   float price; //map with order_details.price.usd
}

*UPDATE: Sorry for unclear question. I am developer for both Objective-C and Java. When I work with JSONModel in ObjC, It's easy to config the mapping like this: https://github.com/icanzilb/JSONModel#key-mapping

I hate to parse JSON manually using getJSONObject(), getString(), ... I am finding a way to configure for automatically parsing with Gson for Java.

Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165

2 Answers2

0

Ofcourse. You can do it by using GSON library. You need to crate 2 pojo and the one which is at outside can have custom model.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30
0

You can try modify your model like this:

public class Order {

    int id; // rename
    String name; //map with order_details.name
    float price; //map with order_details.price.usd

    public void parce(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            id = jsonObject.getInt("order_id");
            name = jsonObject.getJSONArray("order_details").getJSONObject(0).getString("name");
            price = (float) jsonObject.getJSONArray("order_details").getJSONObject(0).getJSONObject("price").getDouble("usd");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Example to using this code:

Order order = new Order();
order.parce("{\"order_id\":104,\"order_details\":[{\"name\":\"Product#1\",\"price\":{\"usd\":12.95}}]}");

Result:

Result

walkmn
  • 2,322
  • 22
  • 29