Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 325
Jonathan Avatar asked Oct 05 '22 07:10

Jonathan


1 Answers

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.

like image 123
MikO Avatar answered Oct 10 '22 03:10

MikO