kadir
kadir

Reputation: 1417

Deserialize objects to plain string

Is It possible to deserialize a json to POJO's while some of the children objects remain a json string? Example:

{
  a_num: 5,
  an_object : { ... },
  a_string: "a cool string"
}

to a POJO with:

int a_num;
//instead of: ObjectType an_object;
String an_object;
String a_string;

Upvotes: 1

Views: 121

Answers (2)

kadir
kadir

Reputation: 1417

From the answer of Jigar I could deduce a simpler solution for this case of problem.

A very easy way to save the time of mapping every variable is to write a deserializer for the string class and then declare the wanted variable as a string.

public class StringDeserializer implements JsonDeserializer<String> {

    @Override
    public String deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return jsonElement.toString();
    }
}

While using following POJO:

int a_num;
String an_object;
String a_string;

And finally registering the TypeAdapter:

private static Gson gson = new GsonBuilder()
  .registerTypeAdapter(String.class, new StringDeserializer()).create();

With this deserializer it is possible to deserialize any field you want as a string. Just type it to a string in the POJO.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

You can write custom deserializer for gson api you can implement JsonDeserializer

for example:

public class MyClass implements JsonDeserializer<MyClass>{

//fields and constructor

@Override
public MyClass deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    JsonObject jobject = (JsonObject) json;

    return new MyClass(
            jobject.get("a_num").getAsInt(), 
            jobject.get("an_object").getAsString(),
            jobject.get("a_string").getAsString() 
    );
}
}

Upvotes: 1

Related Questions