Deserialize array of objects inside another object using Gson - java

Using Volley in my Android project, I am getting a json response like:
{
"value1": 1,
"value2": aaa,
"subvalues": [
{
"value1": 297,
"value2": 310,
"class3": {
"name": "name1",
"id": 1,
"value": 32
}
},
...
]
}
I need to deserialize it to pojo using Gson. Classes are:
class1:
public class class1 {
private int value1;
private String value2;
private List<class2> vals;
public class class2 {
private int value1;
private int value2;
private class3 c3;
}
}
class3:
public class class3 {
private String name;
private int id;
private int value;
}
After calling
Gson g = new Gson();
class1 c1 = g.fromJson(jsonString, class1.class);
I have only value1 and value2 of class1 filled. List remains null all the time.
How can I fix this?

You need to change:
private List<class2> vals;
to:
private List<class2> subvalues;
If you would like to keep vals field original name you can use SerializedName annotation:
public class class1 {
private int value1;
private String value2;
#SerializedName("subvalues")
private List<class2> vals;
...
}
Here you can find more information.

change private List<class2> vals; to private List<class2> subvalues

It's because in JSON your referring as subvalues and in java object your field name as vals. change it to subvalues it'll work.

As the other answers state, you're not naming your variables correctly for gson to be able to deserialize properly. Note that you seemingly have a typo in your returned json as well in class two, referring to calss3 instead of class3.

Related

Java iterate over class fields to create other class

I have a class like this:
public class Example {
private String a;
private Integer b;
private Boolean c;
private List<AnotherClass> d;
}
and I want to convert it to something like this:
[
{
name: "a",
value: "a value"
},
{
name: "b",
value: "1",
},
{
name: "c",
value: "true",
}
]
So, I create a class like this:
public class Test {
private String name;
private String value;
}
I want to have a method to iterate through the Example class so it will produce the Test class without including d attribute. How to achieve that?
This is something you can do easily with reflection. In the example below, I renamed class Test to Property because it represents a key-value pair. If you are happy with using whatever toString() returns as the value for a field, then the solution is pretty simple:
public class Property {
private final String name;
private final String value;
public Property(String name, String value) {
this.name = name;
this.value = value;
}
public static List<Property> toProperties(Object object, String... fieldNames)
throws ReflectiveOperationException
{
ArrayList<Property> properties = new ArrayList<>();
for( String fieldName : fieldNames ) {
Field field = object.getClass().getDeclaredField(fieldName);
properties.add(new Property(fieldName, field.get(object).toString()));
}
return properties;
}
public String toString() {
return String.format("%s: \"%s\"", name, value);
}
}
This sample requires you to specify the names of the desired fields explicitly, for example:
List<Property> properties = Property.toProperties(myExample, "a", "b", "c");
If you'd rather have the fields be auto-detected based on some criterion (for example all primitive and String-typed fields, then you could add this logic within toProperties and get rid of the varargs.
you would need to have some appropriate getters in class Example, and a proper constructor in class Test to initialize the object instance variables like
public Test (String name, int value) {
this.name = name;
this.value = value'
}
Then for each instance of class Example - lets say you have multiple of those in an array or list - you could iterate over them, retrieve the values you want via the getter methods, and initialize one Test object for each one, eg
List<Test> yourListOfTestInstances = new ArrayList<>();
for (Example exampleObject : yourExampleObjectsListOrArray) {
yourListOfTestInstances.add(new Test(exampleObject.getA() , exampleObject.getB()));
}
Then for each created Test instance inside your ArrayList, you could easily build your JSON as needed (even though I do not fully understand why you even need at all this intermediate Test class to do that)

How to exclude particular field name in gson

I am building json for highchart using gson api.
"series": [
{
"name": "tesT",
"data": [["1",12345678], ["2",4534534], ["3",2345678], ["4",456345], ["5",342342]]
}
]
My pojo class is
public class Series {
private String name;
private List<Data> data; // Not working
// getters and setters
}
public class Data {
private String name;
private Double value;
// getters and setters
}
I am getting the output for data like [[name: "1", value: 12345678],[name: "2", value: 4534534]...].
Expected output is [["1",12345678], ["2",4534534]....].
What datatype i should use for the data attribute in the Series class?
Declare a class with a String and a double as data type and define the your list as a holder of that class.
I.e.
public class MyData {
private String nameString;
private Double myDouble;
....
....
}
And in the class Series:
private List<MyData> data;
....
Answer is two dimensional array.
Since i am having two different datatypes inside the two dimensional array i have used Object[][]
public class Series {
private String name;
private Object[][] data;
// getter and setter
}
It works like a charm!!!!!!!!!

Gson.fromJson() throws StackOverflowError

We have this Json:
{
"id": 500,
"field1": "TESTE",
"banco": {
"id": 300,
"descricao": "BANCO_TESTE"
},
"categorias": [
{
"id": 300,
"descricao": "PT",
"publica": true
}
]
}
And my beans:
public class Asking implements Serializable {
private long id;
private String field1;
private Bank bank;
private List<Categoria> categorias;
//[getters and setters]
}
The beans Bank and Categoria:
public class Bank implements Serializable {
private Long code;
private Long id;
private String descricao;
//getters and setters
}
public class Categoria implements Serializable {
private Long code;
private Long id;
private String descricao;
private boolean marcada;
private boolean publica;
//getters and setters
}
When I call:
gson.fromJson(strJson, tokenType);
The error appears:
Method threw 'java.lang.StackOverflowError' exception.
What is wrong?
I can't reproduce this problem. One of two things are wrong here:
Your beans are not defined as you say they are. Check to see if they have other fields hidden within the getter and setter method section. This can happen if you have a circular reference.
You've stated in the comments that this is likely to be your problem. I recommend:
Remove the extra fields from your bean
Create a new class that contains the extra fields, and a field for the Asking instance
Deserialize the Asking instance using Gson, and then pass it into the new class's constructor.
You are doing something unexpected with your setup of the gson.fromJson method. Here's what I'm using that works great:
public static void parseJSON(String jsonString) {
Gson gsonParser = new Gson();
Type collectionType = new TypeToken<Asking>(){}.getType();
Asking gsonResponse = gsonParser.fromJson(jsonString, collectionType);
System.out.println(gsonResponse);
}
Either check your bean class definitions for extra fields, or, failing that, try to make your deserialization match mine.

GSON from json file to object

how can I parse an object that looks like this with GSON:
{ response:
{ value1: 0,
value2: "string",
bigjsonObject: {
value1b: 0,
bigJSONArray: [...]
}
}
All of the examples in GSON have less mixed value types, and the docs mention something about how this can screw up GSON deserialization but don't elaborate and still suggest that GSON can map this to an object.
My current test using gson.fromJSON(inputstream, myObject.class) returns an object with null values, so it is not mapping them.
myObject.class contains an ArrayList of type bigJSONArray
public class myObject {
private ArrayList<bigObjectModel> bigJSONArray;
myObject(){};
}
my assumption is that my ArrayList object doesn't have the types it is looking for, or something. But I am misunderstanding how mapping should work in this case.
In order to parse
{ response:
{ value1: 0,
value2: "string",
bigjsonObject: {
value1b: 0,
bigJSONArray: [...]
}
}
You need the container class to be
public class myObject {
private int value1;
private String value2;
private Foo bigjsonObject;
}
Where the Class Foo is
public class Foo {
private int value1b;
private ArrayList<bigObjectModel> bigJSONArray
}
You may ommit any field and GSON will just skip it

Deserializing inner class with gson returns null

I want to use Gson to Deserialize my JSON into objects.
I've defined the appropriate classes, and some of those class' objects are included in other objects.
When trying to deserialize the whole JSON, I got null values, so I started breaking it apart.
I reached the point where all lower classes stand by them selves, but when trying to deserialize into an object that holds an instance of that smaller object - every thing returns as null.
My partial JSON:
{
"user_profile": {
"pk": 1,
"model": "vcb.userprofile",
"fields": {
"photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
"facebook_url": "https://google.com/facebook",
"site_name": "simple food",
"user": {
"pk": 1,
"model": "auth.user",
"fields": {
"first_name": "blue",
"last_name": "bla"
}
},
"site_url": "https://google.com/"
}
}
}
UserProfile Class:
public class UserProfile {
private int pk;
private String model;
private UPfields fields = new UPfields();//i tried with and without the "new"
}
UPfields Class:
public class UPfields {
private String photo;
private String facebook_url;
private String site_name;
private User user;
private String site_url;
}
User Class:
public class User {
private int pk;
private String model;
private Ufields fields;
}
Ufields Class:
public class Ufields {
private String first_name;
private String last_name;
}
In my main I call:
Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);
So my temp object contain only null values.
I've tried changing the classes to static, and it doesn't work.
The UPfields object and all lower one work fine.
Any suggestions?
when I remove the
"{
"user_profile":"
and it's closing bracket, the deserialize to a user_profile object works.
In order to parse this json example you have to create auxiliary class, which will contain field named user_profile of type UserProfile:
public class UserProfileWrapper {
private UserProfile user_profile;
}
and parse this json string with this class:
UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
Gson starts by parsing the outermost object, which in your case has a single field, user_profile. Your UserProfile class doesn't have a user_profile field, so it can't deserialize it as an instance of that class. You should try to deserialize the value of the user_profile field instead.

Categories

Resources