how to parse JSON file with GSON

前端 未结 3 733
名媛妹妹
名媛妹妹 2020-11-29 02:55

I have a very simple JSON with reviews for products, like:

{
  \"reviewerID\": \"A2XVJBSRI3SWDI\", 
  \"asin\": \"0000031887\", 
  \"reviewerName\": \"abigai         


        
相关标签:
3条回答
  • 2020-11-29 03:18

    just parse as an array:

    Review[] reviews = new Gson().fromJson(jsonString, Review[].class);
    

    then if you need you can also create a list in this way:

    List<Review> asList = Arrays.asList(reviews);
    

    P.S. your json string should be look like this:

    [
        {
            "reviewerID": "A2SUAM1J3GNN3B1",
            "asin": "0000013714",
            "reviewerName": "J. McDonald",
            "helpful": [2, 3],
            "reviewText": "I bought this for my husband who plays the piano.",
            "overall": 5.0,
            "summary": "Heavenly Highway Hymns",
            "unixReviewTime": 1252800000,
            "reviewTime": "09 13, 2009"
        },
        {
            "reviewerID": "A2SUAM1J3GNN3B2",
            "asin": "0000013714",
            "reviewerName": "J. McDonald",
            "helpful": [2, 3],
            "reviewText": "I bought this for my husband who plays the piano.",
            "overall": 5.0,
            "summary": "Heavenly Highway Hymns",
            "unixReviewTime": 1252800000,
            "reviewTime": "09 13, 2009"
        },
    
        [...]
    ]
    
    0 讨论(0)
  • 2020-11-29 03:24

    You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

    private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
    }.getType();
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new FileReader(filename));
    List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
    data.toScreen(); // prints to screen some values
    
    0 讨论(0)
  • 2020-11-29 03:31

    In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

    Try out this code:

    public HashMap<String, String> myMethodName() throws FileNotFoundException
    {
        String path = "absolute path to your file";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
    
        Gson gson = new Gson();
        HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
        return json;
    }
    
    0 讨论(0)
提交回复
热议问题