How to read Json using Gson in java [closed]

2019-05-18 20:31发布

I'm required to read a Json file, using the Gson library, in Java. First I don't understand what a Json file is, what I have is the following: (sorry for the lack of spaces, that's how it was pasted)

{
"initialStorage": [
{shoeType: "red-boots", amount: 10},
{shoeType: "green-flip-flops", amount: 7}
],
services: {
time: {
speed: 1000,
duration: 24
},
manager: {
discountSchedule: [
{shoeType: "red-boots", amount: 1, tick: 3},
{shoeType: "green-flip-flops", amount: 3, tick:10}
]
},
factories: 3,
sellers: 2,
customers: [
{
name: "Bruria",
wishList: ["green-flip-flops"],
purchaseSchedule: [
{shoeType: "red-boots", tick: 3}
]
},
{
name: "Shraga",
wishList: [],
purchaseSchedule: [
{shoeType: "green-flip-flops", tick: 12}
]
}
]
}
}
  1. Do I just put it in java as.. String json = "-pasting it here-"? What is a "Json" file, is it some sort of a file I have to read as nameoffile.json?
  2. How do I use Gson to read it? I didn't understand much from the youtube videos explaining it.

The following link shows the given Json input in a more comfortable way: http://i.stack.imgur.com/r0cTs.png

1条回答
成全新的幸福
2楼-- · 2019-05-18 21:05

JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner. In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.

As a simple example, information about me might be written in JSON as follows:

{
    "age" : "24",
    "hometown" : "Missoula, MT",
    "gender" : "male"
}

To Read the Json file in java using Gson you need to use Gson lib.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Demo : Read data from “file.json“, convert back to object and display it.

package com.mkyong.core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {

    Gson gson = new Gson();

    try {

        BufferedReader br = new BufferedReader(
            new FileReader("c:\\file.json"));

        //convert the json string back to object
        DataObject obj = gson.fromJson(br, DataObject.class);

        System.out.println(obj);

    } catch (IOException e) {
        e.printStackTrace();
    }

    }
}
查看更多
登录 后发表回答