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}
]
}
]
}
}
The following link shows the given Json input in a more comfortable way: https://i.sstatic.net/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:
{
"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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With