I have some json object
{
"name": "John",
"age": 29,
"bestFriends": [
"Stan",
"Nick",
"Alex"
]
}
Here is my implementation of JsonDeserializer:
public class CustomDeserializer implements JsonDeserializer<Person>{
#Override
public Person deserialize(JsonElement json, Type type, JsonDeserializationContext cnxt){
JsonObject object = json.getAsJsonObject();
String name = new String(object.get("name").getAsString());
Integer age = new Integer(object.get("age").getAsInt());
String bestFriends[] = ?????????????????????????????????
return new Person(name, age, bestFriends);
}
}
How to get string array from json object here using GSON library?
Thanks a lot!
For the deserializer you can just loop over the ArrayNode and add the values to your String[] one after another.
ArrayNode friendsNode = (ArrayNode)object.get("bestFriends");
List<String> bestFriends = new ArrayList<String>();
for(JsonNode friend : friendsNode){
bestFriends.add(friend.asText());
}
//if you require the String[]
bestFriends.toArray();
Try this this will work for you. Thanks.
package test;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
class ID{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "ID [id=" + id + "]";
}
}
public class Test {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String jsonText = "{\"id\" : \"A001\"}";
//convert to object
try {
ID id = mapper.readValue(jsonText, ID.class);
System.out.println(id);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to thank all who responded on my question and in the same time i find my decision (which is below) as the most fitting answer. Because i don't need to use any other libraries except GSON.
When i asked my question i didn't know that com.google.gson.TypeAdapter is more efficient instrument than JsonSerializer/JsonDeserializer.
And here below i have found decision for my problem:
package mytypeadapter;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class Main {
static class Person{
String name;
int age;
String[] bestFriends;
Person() {}
Person(String name, int population, String... cities){
this.name = name;
this.age = population;
this.bestFriends = cities;
}
}
public static void main(String[] args) {
class PersonAdapter extends TypeAdapter<Person>{
#Override
public Person read (JsonReader jsonReader) throws IOException{
Person country = new Person();
List <String> cities = new ArrayList<>();
jsonReader.beginObject();
while(jsonReader.hasNext()){
switch(jsonReader.nextName()){
case "name":
country.name = jsonReader.nextString();
break;
case "age":
country.age = jsonReader.nextInt();
break;
case "bestFriends":
jsonReader.beginArray();
while(jsonReader.hasNext()){
cities.add(jsonReader.nextString());
}
jsonReader.endArray();
country.bestFriends = cities.toArray(new String[0]);
break;
}
}
jsonReader.endObject();
return country;
}
#Override
public void write (JsonWriter jsonWriter, Person country) throws IOException{
jsonWriter.beginObject();
jsonWriter.name("name").value(country.name);
jsonWriter.name("age").value(country.age);
jsonWriter.name("bestFriends");
jsonWriter.beginArray();
for(int i=0;i<country.bestFriends.length;i++){
jsonWriter.value(country.bestFriends[i]);
}
jsonWriter.endArray();
jsonWriter.endObject();
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Person.class, new PersonAdapter())
.setPrettyPrinting()
.create();
Person person, personFromJson;
person = new Person ("Vasya", 29, "Stan", "Nick", "Alex");
String json = gson.toJson(person);
personFromJson = new Person();
personFromJson = gson.fromJson(json, personFromJson.getClass());
System.out.println("Name = "+ personFromJson.name);
System.out.println("Age = "+ personFromJson.age);
for(String friend : personFromJson.bestFriends){
System.out.println("Best friend "+ friend);
}
}
}
Related
So I have a JSON document that I want to read with different values including array like below
{ "name": "MacBook", "price": 1299, "stock": 10, "picture": "macbook.jpeg", "categories": [{"id": 1,"name": "macbook"},{"id": 2, "name":"notebook"}]}
I created a couple of POJO java classes to read them:
1 - Class (Product.java)
package models;
import java.util.ArrayList;
public class Product {
String name;
int price;
int stock;
String picture;
public ArrayList<Categories> categories;
public Product(String name, int price, int stock, String picture) {
this.name = name;
this.price = price;
this.stock = stock;
this.picture = picture;
this.categories = new ArrayList<>();
}
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public void setPicture(String picture) {
this.picture = picture;
}
public void setCategories(ArrayList<Categories> categories) {
this.categories = categories;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public int getStock() {
return stock;
}
public String getPicture() {
return picture;
}
public ArrayList<Categories> getCategories() {
return categories;
}
#Override
public String toString() {
return "Product{" +
"productName='" + name + '\'' +
", productPrice=" + price +
", productStock=" + stock +
", productPicture='" + picture + '\'' +
", categories=" + categories +
'}';
}
}
2 Class (Categories.java) to read the array
package models;
public class Categories {
private int id;
private String description;
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public void setId(int id) {
this.id = id;
}
public void setDescription(String description) {
this.description = description;
}
public Categories(int id, String description) {
this.id = id;
this.description = description;
}
#Override
public String toString() {
return "Category{" + "id=" + id + ", description=" + description + '}';
}
}
And this is the main
package p3;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import models.Product;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
String fichero = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/res/FitxersJSON/products.json"))) {
String linea;
while ((linea = br.readLine()) != null) {
fichero += linea;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
Product productObject = gson.fromJson(fichero.toString(), Product.class);
System.out.println(productObject);
}
}
For some reason when I execute the main I get this error
Exception in thread "main" com.google.gson.JsonIOException: JSON document was not fully consumed.
at com.google.gson.Gson.assertFullConsumption(Gson.java:861)
at com.google.gson.Gson.fromJson(Gson.java:854)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at p3.Main.main(Main.java:42)
I have tried formating the JSON document but looks like everything is ok because I can clearly read it printing the "linea" value in each loop.
Thank you in advance.
[EDIT]
I solved the problem by adding "[" and "]" at the beginning and the end of the JSON file and also "," to all lines excepting the last one.
package p3;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import models.Categories;
import models.Product;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
ex2_readProducts();
ex3_addProducts();
}
private static void ex2_readProducts() {
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Product>>() {
}.getType();
String file = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/resources/products.json"))) {
String linea;
System.out.println("***************************** Reading the JSON file *********************************");
while ((linea = br.readLine()) != null) {
file += linea;
}
Collection<Product> enums = gson.fromJson(file, collectionType);
int counter = 0;
for (Product r : enums) {
counter++;
System.out.println("Product nº: " + counter );
System.out.println(r);
}
System.out.println("Result: " + counter + " products read from the file" );
System.out.println("***************************** Finished reading the JSON file *********************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void ex3_addProducts() {
Gson gson = new Gson();
Categories c1 = new Categories(1, "tablet");
Categories c2 = new Categories(2, "game");
Categories c3 = new Categories(3, "phone");
Categories c4 = new Categories(5, "smartwatch");
Categories c5 = new Categories(9, " scooter");
Product p1 = new Product("ipad32", 1200, 23, "ipad32.jpg");
Product p2 = new Product("soccer 3000", 100, 500, "soccer.jpg");
Product p3 = new Product("pixel", 900, 900, "pixel.jpg");
Product p4 = new Product("mi watch", 300, 23, "miwatch.jpg");
Product p5 = new Product("mi scooter 365", 365, 23, "miscooter.jpg");
ArrayList<Categories> categoriesArrayList1;
categoriesArrayList1 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList2;
categoriesArrayList2 = new ArrayList<>(Arrays.asList(c1, c2, c3));
ArrayList<Categories> categoriesArrayList3;
categoriesArrayList3 = new ArrayList<>(Arrays.asList(c1, c4, c3));
ArrayList<Categories> categoriesArrayList4;
categoriesArrayList4 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList5;
categoriesArrayList5 = new ArrayList<>(Arrays.asList(c5, c1));
p1.setCategories(categoriesArrayList1);
p2.setCategories(categoriesArrayList2);
p3.setCategories(categoriesArrayList3);
p4.setCategories(categoriesArrayList4);
p5.setCategories(categoriesArrayList5);
Product[] productsArray = {p1, p2, p3, p4, p5};
try (BufferedWriter br = new BufferedWriter(new FileWriter("src/resources/products2.json"))) {
System.out.println("********************** Adding products to a new file: *********************************");
br.write("[");
br.newLine();
int counter = 0;
for (int i = 0; i < productsArray.length; i++) {
System.out.println("Product nº: " + (i+1) + '\n' + productsArray[i]);
String json = gson.toJson(productsArray[i]);
br.write(json);
if (i != productsArray.length - 1) {
br.write(",");
}
br.newLine();
counter = (i+1);
}
br.write("]");
System.out.println("Result: " + counter + " products added to the file" );
System.out.println("**************************** Finished adding products *****************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
First of all you are using Department instead of Categories in the java class. As I see it contains different fields. I believe your problem is inside the json file or Main class reading the file. Using Guava gives you easier reading files. See my code:
products.json
{
"name": "MacBook",
"price": 1299,
"stock": 10,
"picture": "macbook.jpeg",
"categories": [
{
"id": 1,
"name": "macbook"
},
{
"id": 2,
"name": "notebook"
}
]
}
Main.class
package com.test;
import com.google.common.io.Resources;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
Gson gson = new GsonBuilder()
.create();
String products = Resources.toString(Resources.getResource("products.json"), StandardCharsets.UTF_8).trim();
Product productObject = gson.fromJson(products, Product.class);
System.out.println(productObject);
}
}
output is
Product{name='MacBook', price=1299, stock=10, picture='macbook.jpeg', categories=[Category{id=1, name='macbook'}, Category{id=2, name='notebook'}]}
I think main problem that in json you have {"id": 1,"name": "macbook"} but in java class Categories you use private String description;, how json parser should understand that description and name are same field?
In my opioion, you should try to use name insted of description, for example
package models;
public class Categories {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
...
}
The json looks like:
{
"id": "SMAAZGD20R",
"data": [
{
"blukiiId": "CC78AB5E73C8",
"macAddress": "CC78AB5E73C8",
"type": "SENSOR_BEACON",
"battery": 97,
"advInterval": 1000,
"firmware": "003.007",
"rssi": [
{
"rssi": -96,
"timestamp": 1594642177138
}
],
"beaconSensorData": {
"environment": [
{
"airPressure": 994.4,
"light": 5,
"humidity": 26,
"temperature": 28.4,
"timestamp": 1594642177138
}
]
}
}
]
}
The code looks like:
public class getJSON
{
public static void main(String[] args) throws Exception{
JSONParser parser = new JSONParser();
try{
Object obj = parser.parse(new FileReader("C:\\test.json"));
JSONObject jsonObj = (JSONObject)obj;
JSONArray jsonArr = (JSONArray)jsonObj.get("data");
Iterator itr = jsonArr.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Output:
{"macAddress":"CC78AB5E73C8","rssi":[{"rssi":-96,"timestamp":1594642177138}],"advInterval":1000,"blukiiId":"CC78AB5E73C8","type":"SENSOR_BEACON","battery":97,"firmware":"003.007","beaconSensorData":{"environment":[{"light":5,"airPressure":994.4,"temperature":28.4,"humidity":26,"timestamp":1594642177138}]}}
I get an Array with the object "data", but the array includes only one value with all objects from "data".
How can i address the array "environment" and get the values tempreature, light,...
Have you should try to use a framework like jackson
Who will let unmarshall your json to real java object of your choice
for example :
public class Data
{
private String blukiiId;
private String macAddress;
private String type;
...
private List<RSSI> rssi;
private BeaconSensorData beaconSensorData;
}
With Rssi,BeaconSensorData another class like that etc...
Now your code will get Converted as below
public class getJSON
{
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
// Set any extra configs like ignore fields etc here
try{
Data data = mapper.convertValue(Files.readAllBytes(Paths.get("test.json"), Data.class);
//Now you can access the value as below
data.getBeaconSensorData().getEnvironment().getTemperature();
}catch(Exception e){
e.printStackTrace();
}
}
}
If you can only use org.json.simple.parser.JSONParser, please refer to the following java code by recursion.
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class getJSON
{
private static void visitElement(Object obj, Map<Object, Object> map) throws Exception {
if(obj instanceof JSONArray) {
JSONArray jsonArr = (JSONArray)obj;
Iterator<?> itr = jsonArr.iterator();
while(itr.hasNext())
visitElement(itr.next(), map);
}
else if(obj instanceof JSONObject) {
JSONObject jsonObj = (JSONObject)obj;
Iterator<?> itr = jsonObj.keySet().iterator();
while(itr.hasNext()) {
Object key = itr.next();
Object value = jsonObj.get(key);
map.put(key, value);
visitElement(value, map);
}
}
}
public static void main(String[] args) throws Exception{
JSONParser parser = new JSONParser();
try{
Object obj = parser.parse(new FileReader("C:/test.json"));
Map<Object, Object> map = new HashMap<>();
visitElement(obj, map);
for(Object key : map.keySet())
System.out.println(key + ": " + map.get(key));
}catch(Exception e){
e.printStackTrace();
}
}
}
Look at my code below.
[
{
"title": "Dywizjon 303",
"year": 2019,
"type": "Dokumentalny",
"director": "Zbigniew Zbigniew",
"actors": ["Maria Joao","Jose Raposo"]
},
{
"title": "Szeregowiec Ryan",
"year": 2006,
"type": "Historyczny",
"director": "Stanislaw Stanislaw",
"actors": ["Rosa Canto","Amalia Reis","Maria Garcia"]
},
{
"title": "Duzy",
"year": 1988,
"type": "Dramat",
"director": "Penny Marshall",
"actors": ["Rosa Canto"]
},
{
"title": "Syberiada Polska",
"year": 2013,
"type": "Wojenny",
"director": "Janusz Zaorski",
"actors": ["Harvey Glazer"]
}
]
This is my Entity named Movie
package objectMapper.app;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="Class")
public class Movie {
#JacksonXmlProperty(localName="title")
private String title;
#JacksonXmlProperty(localName="year")
private int year;
#JacksonXmlProperty(localName="type")
private String type;
#JacksonXmlProperty(localName="director")
private String director;
#JacksonXmlProperty(localName="actors")
private String[] actors;
public Movie()
{
}
public Movie(String title, int year, String type, String director, String[] actors) {
this.title = title;
this.year = year;
this.type = type;
this.director = director;
this.actors = actors;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String[] getActors() {
return actors;
}
public void setActors(String[] actors) {
this.actors = actors;
}
#Override
public String toString() {
return "Movie [title=" + title + ", year=" + year + ", type=" + type + ", director=" + director + ", actors="
+ Arrays.toString(actors) + "]";
}
}
Function to read movies.json
public Movie[] readJSONFile() throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper= new ObjectMapper();
Movie[] jsonObj=mapper.readValue(new File("movies.json"),Movie[].class);
return jsonObj;
}
Lets do something with our POJO class
List<String> titles=new ArrayList();
for(Movie itr: tempMovies)
{
titles.add(itr.getTitle().toLowerCase());
}
if(titles.contains(tempTitle.toLowerCase()))
{
for(Movie itr2 : tempMovies)
{
if(tempTitle.toLowerCase().equals(itr2.getTitle().toLowerCase()))
{
System.out.println("Title: "+itr2.getTitle());
System.out.println("Year: "+itr2.getYear());
System.out.println("Type: "+itr2.getType());
System.out.println("Director: "+itr2.getDirector());
String[] tempActorsStrings=itr2.getActors();
int size=tempActorsStrings.length;
for(int i=0;i<size;i++)
{
System.out.println("Actor: "+tempActorsStrings[i]);
}
status=false;
}
}
}
else
{
System.out.println("Movie title does not exist!");
}
I have a scenario to get a child hierarchy structure of a field till parent for doing field level validations.
Can someone provide some solution.
Pojo classes
Student.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.List;
public class Student {
private String studentName;
private List<Subject> subjects;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public List<Subject> getSubjects() {
if (subjects == null) {
return new ArrayList<>();
}
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
}
Subject.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.List;
public class Subject {
private String subjectName;
private List<RevisionMarks> revisionMarks;
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public List<RevisionMarks> getRevisionMarks() {
if (revisionMarks == null) {
return new ArrayList<>();
}
return revisionMarks;
}
public void setRevisionMarks(List<RevisionMarks> revisionMarks) {
this.revisionMarks = revisionMarks;
}
}
RevisionMarks.java
package com.poc.next.validations;
public class RevisionMarks {
private Integer mark;
private String revision;
public Integer getMark() {
return mark;
}
public void setMark(Integer mark) {
this.mark = mark;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
}
Now we are adding a validation to check whether the given mark in RevisionMarks class in valid or not. if it is equal to zero I have to add it to error dto and send it back to UI. The challenge here is i have to provide the field name dynamic in hierarchy like "subjects[0].revisionMarks[0].mark".
Main class
RevisionValidation.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RevisionValidation {
public static void main(String[] args) {
Student student = populateStudentData();
Iterator<Subject> iterator = student.getSubjects().iterator();
while (iterator.hasNext()) {
Subject subject = (Subject) iterator.next();
RevisionMarks revisionMarks = subject.getRevisionMarks().get(0);
System.out.println(revisionMarks.getMark());
if (revisionMarks.getMark() == 0) {
ErrorDTO errorDTO = new ErrorDTO(true, "Invalid Marks", "Error", "subjects[0].revisionMarks[0].mark",
"invalid_mark");
System.out.println(errorDTO);
}
}
}
private static Student populateStudentData() {
List<RevisionMarks> revisionMarks = new ArrayList<>();
RevisionMarks revisionMark = new RevisionMarks();
revisionMark.setMark(0);
revisionMark.setRevision("Test 1");
revisionMarks.add(revisionMark);
List<Subject> subjects = new ArrayList<>();
Subject subject = new Subject();
subject.setSubjectName("CS");
subject.setRevisionMarks(revisionMarks);
subjects.add(subject);
Student student = new Student();
student.setStudentName("Sample");
student.setSubjects(subjects);
return student;
}
}
How can I dynamically create the fieldpath like "subjects[0].revisionMarks[0].mark".
Any suggestions are welcome. Thanks in advance.
Use a counter:
int counter = 0;
Iterator<Subject> iterator = student.getSubjects().iterator();
while (iterator.hasNext()) {
Subject subject = (Subject) iterator.next();
RevisionMarks revisionMarks = subject.getRevisionMarks().get(0);
System.out.println(revisionMarks.getMark());
if (revisionMarks.getMark() == 0) {
ErrorDTO errorDTO = new ErrorDTO(true, "Invalid Marks", "Error", "subjects[" + counter + "].revisionMarks[0].mark",
"invalid_mark");
System.out.println(errorDTO);
}
++counter;
}
I would suggest to use JSR3 validation instead of reinventing wheel.
https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
You can add necessary annotations for each field in your POJO and add #Valid annotation to let validator check nested POJO objects.
The link
https://www.beyondjava.net/blog/how-to-invoke-jsr-303-bean-validation-programmatically/ shows how to call the validator programmatically.
With the validation you can provide any messages and localize them, and the xpaths are built automatically pointing problems in POJO or nested POJOs.
I'm trying to move from default Json API in Android to GSON (or Jackson). But I'm stuck at trying to convert JSONObject to Java object. I've read many tutorials, but found nothing helpful.
I have these two classes (these are just for simplicity):
public class Animal {
#SerializedName("id")
private int id;
//getters and setters
}
public class Dog extends Animal{
#SerializedName("Name")
private String name;
//getters and setters
}
The JSON that I'm trying to map to Dog class is this:
{
"id" : "1",
"Name" : "Fluffy"
}
I'm using this code:
Gson gson = new Gson();
Dog dog = gson.fromJson(jsonObject.toString(), Dog.class);
Name is being mapped ok, but id is not.
How can I achieve this with GSON (or Jackson) libraries, if it's simpler?
Your code should work fine. Try checking what jsonObject.toString() returns. Whether that matches the actual json or not. Example
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
class Animal {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Animal [id=" + id + "]";
}
}
class Dog extends Animal{
#SerializedName("Name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Dog [name=" + name + ", Id=" + getId() + "]";
}
}
public class GSonParser {
public static void main(String[] args) throws Exception {
String json = "{\"id\" : \"1\", \"Name\" : \"Fluffy\"}";
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json);
Gson gson = new Gson();
Dog dog = gson.fromJson(jsonObject.toString(), Dog.class);
System.out.println(dog); // Prints "Dog [name=Fluffy, Id=1]"
}
}
For Jackson I use this code
private static ObjectMapper configMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withGetterVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withSetterVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withCreatorVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY));
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
private Dog readDog(String json) {
Dog ret = null;
if (json != null) {
ObjectMapper mapper = configMapper();
try {
ret = mapper.readValue(json, Dog.class);
} catch (Exception e) {
Log.e("tag", Log.getStackTraceString(e));
return null;
}
}
return ret;
}
Hope it works for you as well.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
In below JSON, there are two arrays. I want them to be parsed in such a way that I can iterate over them one by one and store the result.
Please find below the content of JSON file.
{
"id": 1,
"firstname": "Katerina",
"languages": [
{
"lang": "en",
"knowledge": "proficient"
},
{
"lang": "fr",
"knowledge": "advanced"
}
],
"job": {
"site": "www.javacodegeeks.com",
"name": "Java Code Geeks"
}
}
{
"id": 2,
"firstname": "Kati",
"languages": [
{
"lang": "fr",
"knowledge": "average"
},
{
"lang": "hn",
"knowledge": "advanced"
}
],
"job": {
"site": "www.example.com",
"name": "Php Code Geeks"
}
}
Your JSON is not valid looks like first block is copied to create next block.
Anyway you are using Java then you can use JSONProvider(part of jaxrs library) and use it to convert java object to json or json to java object. You can also use Gson libabry from Google, add the jar in your library or use maven dependency if you are using maven as
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
here is an example of Gson http://www.javacreed.com/simple-gson-example/
I create this example so you can generate:
a valid json file using Gson lib.
read this file and converted it to Object Array java
I hope that's help you
Job Class :
public class Job {
private String site;
private String name;
public Job() {
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Job [site=");
builder.append(site);
builder.append(", name=");
builder.append(name);
builder.append("]");
return builder.toString();
}
}
Class Language :
public class Language {
private String lang;
private String knowledge;
public Language() {
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getKnowledge() {
return knowledge;
}
public void setKnowledge(String knowledge) {
this.knowledge = knowledge;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Language [lang=");
builder.append(lang);
builder.append(", knowledge=");
builder.append(knowledge);
builder.append("]");
return builder.toString();
}
}
Personne class :
import java.util.List;
public class Personne {
private int id;
private String firstname;
private List<Language> languages;
private Job job;
public Personne() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public List<Language> getLanguages() {
return languages;
}
public void setLanguages(List<Language> languages) {
this.languages = languages;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Personne [id=");
builder.append(id);
builder.append(", firstname=");
builder.append(firstname);
builder.append(", languages=");
builder.append(languages);
builder.append(", job=");
builder.append(job);
builder.append("]");
return builder.toString();
}
}
Main Class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class JsonGenerate {
public static void main(String[] args) throws IOException {
List<Personne> personnes = new ArrayList<Personne>();
List<Language> languages = new ArrayList<Language>();
Job job = new Job();
Language lang = new Language();
Personne per = new Personne();
lang.setLang("en");
lang.setKnowledge("proficient");
languages.add(lang);
lang = new Language();
lang.setLang("fr");
lang.setKnowledge("advanced");
languages.add(lang);
job.setName("Java Code Geeks");
job.setSite("www.javacodegeeks.com");
per.setFirstname("Katerina");
per.setId(1);
per.setJob(job);
per.setLanguages(languages);
personnes.add(per);
languages = new ArrayList<Language>();
per = new Personne();
lang = new Language();
lang.setLang("fr");
lang.setKnowledge("average");
languages.add(lang);
lang = new Language();
lang.setLang("hn");
lang.setKnowledge("advanced");
languages.add(lang);
job.setName("Php Code Geeks");
job.setSite("www.example.com");
per.setFirstname("Kati");
per.setId(2);
per.setJob(job);
per.setLanguages(languages);
personnes.add(per);
//System.out.println(personnes.toString());
Writer writer = new FileWriter("Output.json");
Gson gson = new GsonBuilder().create();
gson.toJson(personnes, writer);
writer.close();
BufferedReader bufferedReader = new BufferedReader(new FileReader("Output.json"));
Type collectionType = new TypeToken<List<Personne>>() {}.getType();
//convert the json string back to object
List<Personne> obj = gson.fromJson(bufferedReader, collectionType);
System.out.println(obj);
}
}