Field of custom object not serializing through gson - java

In my app I use gson to save a list of custom objects List<AppBasicView> appViews. The objects are instances of AppBasicView (AppBasicView objects and child objects of that class).
The AppBasicView class is built like that:
public class AppBasicView {
enum BasicViewType {ImageView}
private BasicViewType mBasicViewType;
private LinearLayout.LayoutParams mLayoutParams;
public AppBasicView(BasicViewType basicViewType, LinearLayout.LayoutParams layoutParams) {
this.mBasicViewType = basicViewType;
this.mLayoutParams = layoutParams;
}
...
(getters&setters)
}
AppTextView - the child class of AppBasicView, is built like that:
public class AppTextView extends AppBasicView {
enum TextViewType {Button, TextView, EditText}
private TextViewType mTextViewType;
private String mText;
public AppTextView(TextViewType textViewType, LinearLayout.LayoutParams layoutParams, String mText) {
super(null, layoutParams);
this.mTextViewType = textViewType;
this.mText = mText;
}
...
(getters&setters)
}
I'm saving the list like that:
Gson gson = new Gson();
String json = gson.toJson(appViews);
spEditor.putString("app1objects", json);
spEditor.apply();
Problem 1
The json string I get when saving AppBasicView object contains only the mBasicViewType field (and doesn't contain mLayoutParams field).
And when I save AppBasicView child, the json string contains only child's additional fields and doesn't contain any of the parents (AppBasicView) fields (neither mBasicViewType nor mLayoutParams).
Can't understand why I'm not getting those fields serialized.
Problem 2
After deserialization I get the objects list with only AppBasicView views (even if they where AppTextView) that are not recognized as child objects of AppBasicView (for an AppBasicView v that was AppTextView, v instanceof AppTextView returns false).
This is the deserialization code:
String json = appDataPreferences.getString("app1objects", "");
Type listType = new TypeToken<ArrayList<AppBasicView>>(){}.getType();
if(!json.equals("null"))
appViews = new Gson().fromJson(json, listType);
How can I get the full children object and use them as they were and not as up-casted objects?
Thanks for any help in advance!
This is how I add objects to the list (in case it could help to find the answer):
AppBasicView appBasicView;
if(...)
{
appBasicView = new AppTextView(...);
}
else if(...)
{
appBasicView = new AppBasicView(...);
}
else
throw new CustomExceptions.InvalidDroppingViewTag();
...
appViews.add(appBasicView);
...
Solution 1
Disappeared fields turned out to be all null so gson didn't mention them because:
While serializing, a null field is omitted from the output.
To still see those fields you need to create your Gson like that: Gson gson = new GsonBuilder().serializeNulls().create();

Related

Gson deserialize current object with extended class

I'm new to java (Hum... No... I learned Java at school 10 years ago but never really used it since today).
I have an object class which corresponds to my json and was generated with the website http://www.jsonschema2pojo.org/ (simplified here) :
public class ServerDatasObject {
private Integer error;
private Boolean isOffline;
public Integer getError() {
return error;
}
public Boolean getIsOffline() {
return isOffline;
}
}
And another class used to access all object data (simplified too) :
public class ServerDatasHandler extends ServerDatasObject {
public ServerDatasHandler(String json) {
Gson gson = new Gson();
// how to populate current object using : gson.fromJson(json, ServerDatasObject.class);
}
}
The question is in the code: how to populate current object?
I searched and found something about InstanceCreator :
final Foo existing;
InstanceCreator<Foo> creator = new InstanceCreator<Foo>() {
public Foo createInstance(Type type) { return existing; }
}
Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, creator).create();
Foo value = gson.fromJson(jsonString, Foo.class);
// value should be same as existing
but I don't understand how to use it and if it is what I need.
The final goal is to
{
ServerDatasHandler serverDatasHandler = new ServerDatasHandler (json);
do something with serverDatasHandler.getError()
}
Thanks for your help
You can create a separate static method which creates your handler from json:
public static ServerDatasHandler fromJsonConfig(String json) {
Gson gson = new Gson();
ServerDatasHandler handler = gson.fromJson(json, ServerDatasHandler.class);
return handler;
}
Of course you can also move this method to a factory.
I never used InstanceCreator inside constructor because parsing JSON is almost never a task for a constructor. Preferably it should be hidden inside framework or your own factories. Though, your example with InstanceCreator should also work if you will return ServerDatasHandler.this from the createInstance method.

Gson - deserialize unknown classes

Lets say I have a group of classes A,B,C:
public class A:
int number;
public class B:
int number;
String address;
public class C:
int orderNumber;
How can i deserialize a Json string which contains only these classes, but in an unknown order (using Gson, in Java)? For example:
{//A
"number" : 3
}
//C
{
"orderNumber": 10
}
//B
{
"number" : 5
"address" : "New York"
}
//C
{
"orderNumber": 1
}
Thank you very much!
Answer by pirho is clean and easy if, like he said, your classes are simple as you've provided. But if that isn't the case, you can write your own deserializer.
public class PayloadJsonDeserializer implements JsonDeserializer {
#Override
public Object deserialize(JsonElement elm, Type type, JsonDeserializationContext context) throws JsonParseException {
// create java objects based on the properties in the json object
JsonPrimitive orderNumber = elm.getAsJsonObject().getAsJsonPrimitive("orderNumber");
if(!orderNumber.isJsonNull()) {
return new C(orderNumber.getAsInt());
}
return null;
}
}
Register your custom deserializer with Gson.
GsonBuilder gsonBuilder = new GsonBuilder()
.registerTypeAdapter(PayloadJson.class, new PayloadJsonDeserializer());
Gson gson = gsonBuilder.create();
Use it to deserialize your json.
gson.fromJson(jsonString, PayloadJson[].class);
This is not a generic or anyway a great strategy to do this in general if you have more complex classes with more fields.
But if the classes you want to deserialize are as simple as you provide as an example then create a class having all these fields
#Getter
public class Z {
private Integer orderNumber;
private Integer number;
private String address;
}
You will get a list of Zs and depending on which of the field are null or not null you can -if needed - later construct A, B or C from Z.
If classes to deserialize are more complex you anyway need to create some kind of a mechanism that determines what is the class to parse and to return. It could be like user1516873 suggested in the comment
Collection<Map<String,String>>
so for each item you would need to determine by what fields are present in that map to what class - A,B or C - item would be constructed.

Convert complex Java object to json with gson.toJsonTree

I need to convert a java object (called org) to json format.
The object (DTO ) is a bit complex, because it contains a list of objects of the same class and which in turn can also contain more objects of the same class ( built recursively). When I passing the object to gson.toJsonTree method it seems to fail (there isnt any error), but it seems that the method does not like complex objects). If I set to null the list of objects of the first object everything works fine. I can not modify the class, only the method that makes json.
JsonElement jsonUO = null;
jsonUO = gson.toJsonTree(org,OrgDTO.class);
jsonObject.add("ORG", jsonUO)
public class OrgDTO implements Serializable{
private String id;
......
private List sucesores;
public OrgDTO(){
this.sucesores = new ArrayList();
}
.....
}
It might be a little bit late for the questioner, however I share my answer in case someone else face similar issue:
You'll need to create a helper class that does the json serialization. It should implement the JsonDeserializer:
public class OrgDTOJsonSerializer implements JsonDeserializer<OrgDTO> {
#Override
public JsonElement serialize(OrgDTO src, Type type, JsonSerializationContext jsc) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", src.getId());
/// Build the array of sucesores (whatever it means!)
JsonArray sucesoresArray = new JsonArray();
for (final OrgDTO obj: src.getSucesores()) {
JsonObject succJsonObj = serialize(obj, type, jsc);
sucesoresArray.add(succJsonObj);
}
jsonObject.add("sucesores", sucesoresArray);
return jsonObject;
}
}
Then you'll need to register it in gson before attempting to serialize any object of that type:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(OrgDTO.class, new OrgDTOJsonSerializer());

Is it possible to deserialize JSON property names with periods as a nested object using GSON?

This is an example of the kind JSON I'm trying to consume using GSON:
{
"person": {
"name": "Philip"
"father.name": "Yancy"
}
}
I was wondering if it were possible to deserialize this JSON into the following structure:
public class Person
{
private String name;
private Father father;
}
public class Father
{
private String name;
}
So that:
p.name == "Philip"
p.father.name == "Yancy"
Currently I am using #SerializedName to obtain property names containing a period, e.g.:
public class Person
{
private String name;
#SerializedName("father.name")
private String fathersName;
}
However, that's not ideal.
From looking at the documentation it doesn't appear to be immediately possible but there may be something I have missed - I'm new to using GSON.
Unfortunately I cannot change the JSON I'm consuming and I'm reluctant to switch to another JSON parsing library.
As far as I understand you can't do it in a direct way, because Gson will understand father.name as a single field.
You need to write your own Custom Deserializer. See Gson user's guide instructions here.
I've never tried it, but it doesn't seem to be too difficult. This post could be also helpful.
Taking a look at Gson's user guide and the code in that post, you'll need something like this:
private class PersonDeserializer implements JsonDeserializer<Person> {
#Override
public Person deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jobject = (JsonObject) json;
Father father = new Father(jobject.get("father.name").getAsString());
return new Person(jobject.get("name").getAsString(), father);
}
}
Assuming that you have suitable constructors...
And then:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Person.class, new PersonDeserializer());
Gson gson = gsonBuilder.create();
Person person = gson.fromJson(jsonString, Person.class);
And Gson will call your deserializer in order to deserialize the JSON into a Person object.
Note: I didn't try this code, but it should be like this or something very similar.
I couldn't do this with just Gson. I need a new library 'JsonPath'. I used Jackson's ObjectMapper to convert the object to string but you can easily use Gson for this.
public static String getProperty(Object obj, String prop) {
try {
return JsonPath.read(new ObjectMapper().writeValueAsString(obj), prop).toString();
} catch (JsonProcessingException|PathNotFoundException ex) {
return "";
}
}
// 2 dependencies needed:
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
// https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path
// usage:
String motherName = getProperty(new Person(), "family.mother.name");
// The Jackson can be easily replaced with Gson:
new Gson().toJson(obj)

JSON - deserialization of dynamic object using Gson

Let's imagine I have a Java class of the type:
public class MyClass
{
public String par1;
public Object par2;
}
Then I have this:
String json = "{"par1":"val1","par2":{"subpar1":"subval1"}}";
Gson gson = new GsonBuilder.create();
MyClass mClass = gson.fromJson(json, MyClass.class);
The par2 JSON is given to me from some other application and I don't ever know what are it's parameter names, since they are dynamic.
My question is, what Class type should par2 variable on MyClass be set to, so that the JSON String variable is correctly deserialized to my class object?
Thanks
Check out Serializing and Deserializing Generic Types from GSON User Guide:
public class MyClass<T>
{
public String par1;
public T par2;
}
To deserialize it:
Type fooType = new TypeToken<Myclass<Foo>>() {}.getType();
gson.fromJson(json, fooType);
Hope this help.
See the answer from Kevin Dolan on this SO question: How can I convert JSON to a HashMap using Gson?
Note, it isn't the accepted answer and you'll probably have to modify it a bit. But it's pretty awesome.
Alternatively, ditch the type safety of your top-level object and just use hashmaps and arrays all the way down. Less modification to Dolan's code that way.
if you object has dynamic name inside lets say this one:
{
"Includes": {
"Products": {
"blablabla": {
"CategoryId": "this is category id",
"Description": "this is description",
...
}
you can serialize it with:
MyFunnyObject data = new Gson().fromJson(jsonString, MyFunnyObject.class);
#Getter
#Setter
class MyFunnyObject {
Includes Includes;
class Includes {
Map<String, Products> Products;
class Products {
String CategoryId;
String Description;
}
}
}
later you can access it:
data.getIncludes().get("blablabla").getCategoryId()
this code:
Gson gson = new GsonBuilder.create();
should be:
Gson gson=new Gson()
i think(if you are parsing a json doc).

Categories

Resources