Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse inner json string as nested class using retrofit

I have used retrofit with nested classes before, but the current api I'm tring to use has such a structure:

Request body:

{
   "Id" : "a2",
   "messageCode" : 1,
   "bigNestedClass" : "{\"field1\":238,\"otherField\":246,\"ip\":\"10.255.130.154\",\"someOtherField\":15,\"Info\":1501069568}"
}

and a similar response body.

Note that bigNestedClass is a string.

I created different pojo classes for request and response. However, creating a nested BigNestedClass makes this field filled as JSON object, as expected, not a JSON string. And I have same problem parsing the response too.

My question: Is there a way in retrofit that enables encode, parse nested classes as strings?

I use Retrofit 2.0
I use gson (can be changed)

like image 816
t.m. Avatar asked Nov 29 '25 00:11

t.m.


1 Answers

With gson I would simply make this with TypeAdapter. See the class below:

public class MyTypeAdapter extends TypeAdapter<BigNestedClass> {

    private Gson gson = new Gson();

    @Override
    public BigNestedClass read(JsonReader arg0) throws IOException {
        // Get the string value and do kind of nested deserializing to an instance of
        // BigNestedClass
        return gson.fromJson(arg0.nextString(), BigNestedClass.class);
    }

    @Override
    public void write(JsonWriter arg0, BigNestedClass arg1) throws IOException {
        // Get the instance value and insted of normal serializing make the written
        // value to be a string having escaped json
        arg0.value(gson.toJson(arg1));
    }

}

Then you would only need to register MyTypeAdapter with gson, like:

private Gson gson = new GsonBuilder()
    .registerTypeAdapter(BigNestedClass.class, new MyTypeAdapter())
    .create();

To have retrofit to use it you would need to do just a bit more when creating it:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
like image 109
pirho Avatar answered Dec 01 '25 15:12

pirho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!