0

I have a Model consisting in a main Manager class, which has some variables, for example name but also has a big object called data. For a special case I want to pass from json to Model with Gson but ignoring the data Object of the json (for the normal case I will decode completely all the objects of the json).

I need to do this without anotations and without transient, just adding a deserializing rule to exclude Data class in case I want to do it.

How can I specify ad decode time that I want to ignore a class?

My model:

public class Manager{
    String name;
    Data data;
}

public class Data{
    String dummy;
    String dummy2;
}

Json sample:

{"manager":{"name":"testname","data":{"dummy":"testname", "dummy2":"testname2"}}} 

Code sample that decodes all:

GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
                .addType(Data.class)
                .addType(Manager.class)
                .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
Manager manager = gson.fromJson(json, Manager.class);
NullPointerException
  • 36,107
  • 79
  • 222
  • 382
  • Register a type adapter which (somehow) is made aware of if it’s a ‘special case’ and then doesn’t do anything with the `data` field? – BeUndead Nov 28 '19 at 02:17
  • You need this in a release version? – G. Ciardini Nov 28 '19 at 15:03
  • And what is a special case? Can it change during program run? Maybe https://stackoverflow.com/questions/23920740/remove-empty-collections-from-a-json-with-gson/ will help you (there a JSON was cleared from empty collections). – CoolMind Nov 28 '19 at 15:25

1 Answers1

0

Fortunately for you, I banged my head last week to sort out a derivative of what you're trying to achieve. So as i mention in this post there is a little trick in the release version that maybe suite what are you trying to do:

Apparently the toString() method inside the parsed class is needed to make the Gson library work.

The toString() method expose the class to the serialization.

Having said that if you use a release version and don't add any proguard rules you can use the following method to exclude data:

@Override
public String toString() {
    return "Manager{" +
            "name='" + name + '\'}';
}
G. Ciardini
  • 1,210
  • 1
  • 17
  • 32