Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a JSON file which has multiple root elements using Gson library in Java?

Tags:

java

json

gson

I have a JSON file like this,

JSON File

{
    "reviewerID": "A7S2B0I67WNWB", 
    "asin": "0594481813", 
    "reviewerName": "AllyMG", 
    "helpful": [2, 2], 
    "reviewText": "This item is just as was described in the original description, works without any issues to be seen. Good product", 
    "overall": 4.0, 
    "summary": "As expected", 
    "unixReviewTime": 1397606400, 
    "reviewTime": "04 16, 2014"
}
{
    "reviewerID": "A3HICVLF4PFFMN", 
    "asin": "0594481813", 
    "reviewerName": "Amazon Customer", 
    "helpful": [0, 0], 
    "reviewText": "bought for a spare for my 9" Nook HD and it fit perfectly.  Very satisfied with the price much less than on the BN site", 
    "overall": 5.0, 
    "summary": "great fit", 
    "unixReviewTime": 1399248000, 
    "reviewTime": "05 5, 2014"
}
{
    "reviewerID": "ANSKSPEEAKY7S", 
    "asin": "0594481813", 
    "reviewerName": "Gena", 
    "helpful": [1, 1], 
    "reviewText": "My son crewed my HD charger cord so I needed another one, this is exactly like the one my son destroyed.", 
    "overall": 5.0, 
    "summary": "Works Great", 
    "unixReviewTime": 1372032000, 
    "reviewTime": "06 24, 2013"
}

And I want to print the values of reviewText in all three of them.

I have a Java code like this,

Java Code:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class ReviewText {

    public static void main(String[] args) throws FileNotFoundException {

        JsonParser parser = new JsonParser();
        JsonReader jsonReader = new JsonReader(new FileReader("sample.json"));

        JsonElement jsonTree = parser.parse(jsonReader);

        JsonObject jsonObject = jsonTree.getAsJsonObject();

        JsonElement f1 = jsonObject.get("reviewText");

        System.out.println(f1);

    }
}

But my code prints the output only for the first item. How do I print the value of reviewTextfor all three of them?

Is my JSON file in the correct format?

like image 936
Kemat Rochi Avatar asked Oct 26 '16 04:10

Kemat Rochi


People also ask

How do I iterate through a JSON file in Python?

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict.

How do I read a JSON object in Java?

Gson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonElement or JsonObject and are provided by Gson. Start by instantiating a JsonParser then call .parse to get a JsonElement which can be descended through to retrieve nested values.

How do I loop through a JSON file with multiple keys?

How do I loop through a JSON file with multiple keys/sub-keys in Python? You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict.

How to convert a JSON array to an iterable array?

We can use Object.entries () to convert a JSON array to an iterable array of keys and values. Object.entries (obj) will return an iterable multidimensional array. We can use this output to find our keys and values in a bunch of different ways. Similarly, Object.keys (obj) returns an iterable list of keys.


2 Answers

Use a JsonStreamParser to handle multiple top-level elements in the file.

JsonStreamParser parser = new JsonStreamParser(new FileReader("sample.json"));

while (parser.hasNext()) {
    JsonElement object = parser.next();
    System.out.println(object.getAsJsonObject().get("reviewText"));
}
like image 92
xiaofeng.li Avatar answered Sep 19 '22 13:09

xiaofeng.li


If your JSON file were structured like this, [{}, {}, {}, ...], you could read it as a JSON array and iterate through it.

[
    {
        "reviewerID": "A7S2B0I67WNWB", 
        "asin": "0594481813", 
        "reviewerName": "AllyMG", 
        "helpful": [2, 2], 
        "reviewText": "This item is just as was described in the original description, works without any issues to be seen. Good product", 
        "overall": 4.0, 
        "summary": "As expected", 
        "unixReviewTime": 1397606400, 
        "reviewTime": "04 16, 2014"
    },
    {
        "reviewerID": "A3HICVLF4PFFMN", 
        "asin": "0594481813", 
        "reviewerName": "Amazon Customer", 
        "helpful": [0, 0], 
        "reviewText": "bought for a spare for my 9" Nook HD and it fit perfectly.  Very satisfied with the price much less than on the BN site", 
        "overall": 5.0, 
        "summary": "great fit", 
        "unixReviewTime": 1399248000, 
        "reviewTime": "05 5, 2014"
    }
]
like image 34
neurite Avatar answered Sep 19 '22 13:09

neurite