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);
2
  • What is your problem? are you freezing in mapping part? Commented Apr 30, 2017 at 2:33
  • System.out.println(jsonObject.getAsJsonArray("product")); prints null Commented Apr 30, 2017 at 3:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.