Harley
Harley

Reputation: 1524

Java GSON - make array from String of json

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

Upvotes: 1

Views: 1438

Answers (3)

pantos27
pantos27

Reputation: 629

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

Upvotes: 0

tima
tima

Reputation: 1513

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.

Upvotes: 1

CharukaK
CharukaK

Reputation: 396

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

Upvotes: 0

Related Questions