Can someone give and example of how to do the following program ? Write a Java p
ID: 3886734 • Letter: C
Question
Can someone give and example of how to do the following program ?Write a Java program that will read the JSON file SampleFile.json, parse it with the gson library and a set of Java methods. Can someone give and example of how to do the following program ?
Write a Java program that will read the JSON file SampleFile.json, parse it with the gson library and a set of Java methods.
Write a Java program that will read the JSON file SampleFile.json, parse it with the gson library and a set of Java methods.
Explanation / Answer
Please find my implementation.
########## SampleFile.json ########
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
################ Java Code #############
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class JsonReader {
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
JsonParser parser = new JsonParser();
JsonArray a = (JsonArray) parser.parse(new FileReader("SampleFile.json"));
for (Object o : a)
{
JsonObject person = (JsonObject) o;
JsonElement name = person.get("name");
System.out.println("Name: "+name);
JsonElement city = person.get("city");
System.out.println("City: "+city);
JsonElement job = person.get("job");
System.out.println("Job: "+job);
JsonArray cars = (JsonArray) person.get("cars");
System.out.print("Cars: ");
for (Object c : cars)
{
System.out.print(c+" ");
}
System.out.println(" ");
}
}
}
/*
Sample run:
Name: "John"
City: "Berlin"
Job: "Teacher"
Cars: "audi" "bmw"
Name: "Mark"
City: "Oslo"
Job: "Doctor"
Cars: "VW" "Toyata"
*/