0

I have a json object which I want to parse in java and use data as string. JSON Object goes like this:

[
  {
    "id": 74168,
    "billing": {
      "first_name": "Tushar",
      "last_name": "Attar",
      "phone": "12345678",
      "address_1": "myaddress1",
      "address_2": "myaddressline2",
      "city": "mycity",
      "state": "mystate",
      "postcode": "500050"
    },
    "line_items": [
      {
        "name": "Adidas track pants",
        "quantity": 1,
        "meta": [
          {
            "value": "500 grams"
          }
        ]
      },
      {
        "name": "reebok track pants",
        "quantity": 1,
        "meta": [
          {
            "value": "500 grams"
          }
        ]
      }
    ]
  }
]

I am using GSON to parse data. Till now I am able to parse id, first name, last name, phone number,address_1, address_2, postcode, state properly. Now I am trying to parse line items array but I get a null pointer exception.

I have searched a lot on google but no success. Can anyone tell me the code to parse the data? Here is the code I am using to parse line items array:

JsonElement jelement = new JsonParser().parse(inputLine);
JsonArray jarray = jelement.getAsJsonArray();

JsonObject  jobject = jarray.get(i).getAsJsonObject();
//coyping this JsonObject to other reference so that it can be used for line items
JsonObject jobject123 = jobject;

JsonArray jarraylist = jobject123.getAsJsonArray("line_items");
String name[] = new String[jarraylist.size()];
String quantity[] = new String[jarraylist.size()];
String weight[] = new String[jarraylist.size()];

int j;
for( j=0;j<jarraylist.size();j++) {
    JsonObject jobjectlist = jarraylist.get(j).getAsJsonObject();
    name[j] = jobjectlist.get("name").getAsString();
    quantity[j] = jobjectlist.get("quantity").getAsString();

    JsonArray jarraymeta = jobjectlist.getAsJsonArray("meta");
    JsonObject  jobjectlist2 = jarraymeta.get(0).getAsJsonObject();
    weight[j] = jobjectlist2.get("value").getAsString();
}

The inputline contains the JSON object as string

Boris Schegolev
  • 3,418
  • 5
  • 19
  • 32

0 Answers0