Java reading JSON with multiple objects - java

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!");
}

Related

How to get string array from json object in deserialize method

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);
}
}
}

Map JSON to Java object

I have these type of JSON object which I'm getting from gridx filter expression:
{
"op": "or",
"data": [
{
"op": "contain",
"data": [
{
"op": "string",
"data": "id",
"isCol": true
},
{
"op": "string",
"data": "sdfv"
}
]
},
{
"op": "contain",
"data": [
{
"op": "string",
"data": "post",
"isCol": true
},
{
"op": "string",
"data": "sdfv"
}
]
},
{
"op": "contain",
"data": [
{
"op": "string",
"data": "birthday",
"isCol": true
},
{
"op": "string",
"data": "sdfv"
}
]
}
]
}
How I can map this to a Java object and then deserialize using Gson?
I've made these two classes:
package dto.Filter;
public class FilterData extends FilterExpression {
private String op;
private boolean isCol;
private String data;
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public boolean isCol() {
return isCol;
}
public void setCol(boolean col) {
isCol = col;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package dto.Filter;
import java.util.List;
public class FilterExpression {
private List<FilterData> filters;
private String op;
public List<FilterData> getFilters() {
return filters;
}
public void setFilters(List<FilterData> filters) {
this.filters = filters;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
}
The problem is that I have both data as Object and String type. Do I need to use my custom TypeAdapter?
Make your data structure as
class DataStructure {
private String op;
private String data;
private String isCol;
public DataStructure(){
op="";
data="";
isCol="";
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String isCol() {
return isCol;
}
public void setCol(String isCol) {
this.isCol = isCol;
}
#Override
public String toString() {
return "DataStructure [op=" + op + ", data=" + data + ", isCol=" + isCol + "]";
}
}
I have parse the JSON file using google GSON library. Here is maven repository.
Note: to read using GSON library add '[' at starting and ']' at ending.
I have read the JSON file and store the data in ArrayList. Hope after getting array list you can do serialization.
public class FilterData {
private static Gson gson = new Gson();
private static JsonParser parser = new JsonParser();
public static List<DataStructure> getData(List<DataStructure> datas){
List<DataStructure> result = new ArrayList<>();
for (DataStructure data : datas) {
for (JsonElement object : parser.parse(data.getData()).getAsJsonArray()) {
DataStructure dataStructure = new DataStructure();
JsonObject jObject = gson.fromJson(object, JsonObject.class);
dataStructure.setOp(jObject.get("op").toString());
dataStructure.setData(jObject.get("data").toString());
if (jObject.has("isCol"))
dataStructure.setData(jObject.get("isCol").toString());
System.out.println(dataStructure);
result.add(dataStructure);
}
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream("input.json")));
List<DataStructure> datas = new ArrayList<>();
JsonArray jArray = parser.parse(reader).getAsJsonArray();
for (JsonElement object : jArray) {
DataStructure dataStructure = new DataStructure();
JsonObject jObject = gson.fromJson(object, JsonObject.class);
dataStructure.setOp(jObject.get("op").toString());
dataStructure.setData(jObject.get("data").toString());
if (jObject.has("isCol"))
dataStructure.setData(jObject.get("isCol").toString());
System.out.println(dataStructure);
datas.add(dataStructure);
}
List<DataStructure> insideData = getData(datas);
List<DataStructure> inside2Data = getData(insideData);
}
}

Get nested JSON object with GSON : Deserialization

I have gone through the threads from SOF which talks about getting nested JSON using GSON. Link 1 Link 2. My JSON file is as shown below
{
"Employee_1": {
"ZipCode": 560072,
"Age": 50,
"Place": "Hawaii",
"isDeveloper": true,
"Name": "Mary"
},
"Employee_2": {
"ZipCode": 560072,
"Age": 80,
"Place": "Texas",
"isDeveloper": true,
"Name": "Jon"
}
}
my classes are as shown below
public class Staff {
String Employee_1 ;
}
class addnlInfo{
String Name;
String Place;
int Age;
int Zipcode;
boolean isDeveloper;
}
The deserializer class which I built is as shown below
class MyDeserializer implements JsonDeserializer<addnlInfo>{
public addnlInfo deserialize1(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("Employee_1");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, addnlInfo.class);
}
#Override
public TokenMetaInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
// TODO Auto-generated method stub
return null;
}
The main file
Gson gson = new GsonBuilder()
.registerTypeAdapter(addnlInfo.class, new MyDeserializer())
.create();
String jsonObject= gson.toJson(parserJSON);
addnlInfo info= gson.fromJson(jsonObject, addnlInfo .class);
System.out.println(info.Age + "\n" + info.isDeveloper + "\n" + info.Name + "\n" + info.Place);
Staff parentNode = gson.fromJson(jsonObject, Staff.class);
System.out.println(parentNode.Employee_1);
The problem:
My Subparent element (e.g. 'Employee_1') keeps changing. Do I have to construct multiple deserializers?
Also, I get "Expected a string but was BEGIN_OBJECT" which I understand as we use nestedJSON.
I am not sure how your classes translate to your JSON, but you are making this too complex.
I renamed fields and class names to adhere to Java standards.
Main.java
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class Main {
public static void main(String[] args) {
Map<String, Staff> employees = new LinkedHashMap<String, Staff>();
employees.put("Employee_1", new Staff(new Info("Mary", "Hawaii", 50, 56072, true)));
employees.put("Employee_2", new Staff(new Info("Jon", "Texas", 80, 56072, true)));
String jsonString = new GsonBuilder().setPrettyPrinting().create().toJson(employees);
System.out.println("# SERIALIZED DATA:");
System.out.println(jsonString);
Type mapOfStaff = new TypeToken<Map<String, Staff>>() {}.getType();
Map<String, Staff> jsonObject = new Gson().fromJson(jsonString, mapOfStaff);
System.out.println("\n# DESERIALIZED DATA:");
for (Entry<String, Staff> entry : jsonObject.entrySet()) {
System.out.printf("%s => %s%n", entry.getKey(), entry.getValue());
}
}
}
Staff.java
public class Staff {
private Info info;
public Staff(Info info) {
this.info = info;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
#Override
public String toString() {
return String.format("Staff [info=%s]", info);
}
}
Info.java
public class Info {
private String name;
private String place;
private int age;
private int zipcode;
private boolean developer;
public Info(String name, String place, int age, int zipcode, boolean developer) {
this.name = name;
this.place = place;
this.age = age;
this.zipcode = zipcode;
this.developer = developer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public boolean isDeveloper() {
return developer;
}
public void setDeveloper(boolean developer) {
this.developer = developer;
}
#Override
public String toString() {
return String.format(
"Info [name=%s, place=%s, age=%d, zipcode=%d, developer=%b]",
name, place, age, zipcode, developer
);
}
}
Output
# SERIALIZED DATA:
{
"Employee_1": {
"info": {
"name": "Mary",
"place": "Hawaii",
"age": 50,
"zipcode": 56072,
"developer": true
}
},
"Employee_2": {
"info": {
"name": "Jon",
"place": "Texas",
"age": 80,
"zipcode": 56072,
"developer": true
}
}
}
# DESERIALIZED DATA:
Employee_1 => Staff [info=Info [name=Mary, place=Hawaii, age=50, zipcode=56072, developer=true]]
Employee_2 => Staff [info=Info [name=Jon, place=Texas, age=80, zipcode=56072, developer=true]]

Converting JSONArray to List<Object>?

I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.
How could I do this ?
JSON
{ "result" : [
{ "Noticia" : {
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
} },
{ "Noticia" : {
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
} }
] }
Deserializes
List<Noticia> lista = new ArrayList<Noticia>();
Gson gson = new Gson();
JSONArray array = obj.getJSONArray("result");
Type listType = new TypeToken<List<Noticia>>() {}.getType();
lista = gson.fromJson(array.toString(), listType);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
Class Noticia
public class Noticia implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String titulo;
private String descricao;
private String usuario;
private Date created;
private String image;
There are two problems with your code :
First is that you are using a getJsonArray() to get the array,
which isn't part of Gson library, you need to use
getAsJsonArray() method instead.
Second is that you are using array.toString() which isn't obvious
because for the fromJson method you need a jsonArray as
parameter and not String and that will cause you parse problems, just remove it.
And use the following code to convert your jsonArray to List<Noticia> :
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
And your whole code will be:
Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
I think the problem could be something to do with toString() on JSONArray. But are you using obj.getAsJsonArray method?
Try this:
JSONArray arr = obj.getAsJsonArray("result");
Type listType = new TypeToken<List<Noticia>>() {
}.getType();
return new Gson().fromJson(arr , listType);
Noticia.java
public class Noticia {
private String created;
private String descricao;
private String id;
private String image;
private String titulo;
private String usuario;
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
#Override
public String toString() {
return "Noticia [created=" + created + ", descricao=" + descricao
+ ", id=" + id + ", image=" + image + ", titulo=" + titulo
+ ", usuario=" + usuario + "]";
}
}
Result.java
public class Result {
private Noticia Noticia;
public Noticia getNoticia() {
return Noticia;
}
public void setNoticia(Noticia noticia) {
Noticia = noticia;
}
#Override
public String toString() {
return "Result [Noticia=" + Noticia + "]";
}
}
Item.java
import java.util.List;
public class Item {
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
#Override
public String toString() {
return "Item [result=" + result + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
Item r = gson.fromJson(j, Item.class);
System.out.println(r);
}
}
Final result
Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
You parse json, that looks like
{ "result" : [
{
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
},
{
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
}
] }
You need to make another object Item and parse a list of them.
public class Item{
Noticia noticia;
}
Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.
Kotlin Ex :
we getting response in form of JSONArry
call.enqueue(object : Callback<JsonArray> {
override fun onResponse(call: Call<JsonArray>, response: Response<JsonArray>) {
val list = response.body().toString()
val gson = Gson()
val obj: CitiesList? = gson.fromJson(list, CitiesList::class.java)
cityLiveData.value = obj!!
}
override fun onFailure(call: Call<JsonArray>, t: Throwable) {
}
})
Here CitiesList CitiesList::class.java is the ArrayList of Cities object
class CitiesList : ArrayList<CitiesListItem>()
Before using GSON add dependancey in Gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.8'
}

How can i get GSON to parse JSON String

How can I get the GSON library to correctly convert the below JSON string to objects. I've tried for ages but it only seems to pick out the 2 "Word" objects and leave the member fields blank or null.
JSON:
{
"words": [
{
"Word": {
"id": "1",
"word": "submarine",
"word_syllables": "sub-mar-ine",
"picture": "none.jpg",
"soundfile": "",
"user_id": "1"
}
},
{
"Word": {
"id": "2",
"word": "computer",
"word_syllables": "com-pute-r",
"picture": "computer.jpg",
"soundfile": "",
"user_id": "0"
}
}
]
}
I thought that the above could be created simply by having a class called "Words" which contains an arraylist/list of Word objects.
The Words class;
package com.example.testgson.business;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
public class Words {
public List<Word> words=new ArrayList<Word>();
public Words(){
}
public int size(){
return words.size();
}
public void addWord(Word w){
this.words.add(w);
}
public List<Word> getWords() {
return words;
}
public void setWords(List<Word> words) {
this.words = words;
}
public void printAll(){
for(int i=0; i<words.size();i++){
Word w=(Word) words.get(i);
if(w!=null){
Log.d("word",w.getWord());
}
}
}
public List <Word> getWordList(){
return this.words;
}
}
The Word Class;
public class Word {
int id;
String word;
String word_syllables;
String picture;
String soundfile;
int user_id;
public Word(){
}
public Word(int id, String word, String word_syllables, String picture,
String soundfile, int user_id) {
super();
this.id = id;
this.word = word;
this.word_syllables = word_syllables;
this.picture = picture;
this.soundfile = soundfile;
this.user_id = user_id;
}
#Override
public String toString() {
return "Word [id=" + id + ", word=" + word + ", word_syllables="
+ word_syllables + ", picture=" + picture + ", soundfile="
+ soundfile + ", user_id=" + user_id + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
public String getWord_syllables() {
return word_syllables;
}
public void setWord_syllables(String word_syllables) {
this.word_syllables = word_syllables;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getSoundfile() {
return soundfile;
}
public void setSoundfile(String soundfile) {
this.soundfile = soundfile;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
GSON convert code;
Gson gson = new Gson();
Words obj = gson.fromJson(sjson, Words.class);
You need to skip one level, because you array is not a List<Word> but a List<Holder> where the Holder class has a Word instance. You can either create this class, or write a custom deserializer to skip it:
class CustomDeserializer implements JsonDeserializer<Word> {
#Override
public Word deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get("Word");
return new Gson().fromJson(content, type);
}
}
and then:
Gson gson = new GsonBuilder().registerTypeAdapter(Word.class, new CustomDeserializer()).create();
which yields:
Word [id=1, word=submarine, word_syllables=sub-mar-ine, picture=none.jpg, soundfile=, user_id=1]
Word [id=2, word=computer, word_syllables=com-pute-r, picture=computer.jpg, soundfile=, user_id=0]

Categories

Resources