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}
]
}
]
}
}
- 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?
- 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
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:
To Read the
Json
file in java usingGson
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.