1

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;
1
  • Not by default. Write a custom TypeAdapter. Commented Jun 12, 2014 at 17:16

2 Answers 2

1

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() 
    );
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice answer! Could deduce a slightly better solution from it
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.