1

I want to make an array of product objects from a json file which is currently a String.

{
  "invoice": {
    "products": {
      "product": [
        {
          "name": "Food",
          "price": "5.00"
        },
        {
          "name": "Drink",
          "price": "2.00"
        }
      ]
    },
    "total": "7.00"
  }
}

...

String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("product");

the line below give me: java.lang.NullPointerException

for(JsonElement element: jsonArray) {
  //do stuff
  System.out.println(element);
}

some code goes here...

product = new Product(name, price);
List<Product> products = new ArrayList<Product>();
products.add(product);
Amit
  • 30,756
  • 6
  • 57
  • 88
Harley
  • 1,305
  • 1
  • 13
  • 28

3 Answers3

1

You have to traverse the whole JSON string to get to the "product" part.

JsonArray jsonArray = jsonObject.get("invoice").getAsJsonObject().get("products").getAsJsonObject().get("product").getAsJsonArray();

I would recommend that you create a custom deserializer as described in the second answer to this question: How do I write a custom JSON deserializer for Gson? This will make it a lot cleaner, and let you handle improper JSON and make it easier in case your JSON ever changes.

Community
  • 1
  • 1
tima
  • 1,498
  • 4
  • 20
  • 28
0

I think you can use Gson library for this You can find the project and the documentation at : https://github.com/google/gson/blob/master/README.md

CharukaK
  • 366
  • 2
  • 9
0

try

String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject invoice = parser.parse(jsonString).getAsJsonObject();
JsonObject products = invoice.getAsJsonObject("products");
JsonArray jsonArray = products.getAsJsonArray("product");
pantos27
  • 629
  • 4
  • 13