0

I have a class with some fields and extra data of type string that will store a json object. I want it to not be deserialized, but after looking for more than an hour, the only thing I found was:

@Expose(deserialize=false)

But It doesn't work.

The following is an example:

public class Employee implements Serializable
{


    private static final long serialVersionUID = 1L;

    @Expose
    public Long id;
    @Expose
    public String name; 
    ... some more fields

    @SerializedName("extraData")
    @Expose(deserialize = false)
    public String extraData;



}

Then on my service I do the following:

    final GsonBuilder builder = new GsonBuilder();

    final Gson gson = builder.create();

    Employee emp = gson.fromJson(json, Employee.class);

The object I am receiving from the frontend is:

{
 "id":1,
 "name": "John Doe", 
 "extraData": {"someField1":"someValue1","someField2":"someValue2"}
}

And I get this error: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 48 path $.extraData

When I just want to get "extraData" as an string with the value

{"someField1":"someValue1","someField2":"someValue2"}

Other solutions are not accepted because it is the spec i was given.

jsertx
  • 636
  • 7
  • 17

2 Answers2

1

It does not harm if you change the type of extraData like (assuming it is possible and the extra data follows the pattern you described)

public Map<String, String> extraData;

and compose a String of it.

Still what Jaron F suggested might be better in whole. For using type adapter see this answer

pirho
  • 11,565
  • 12
  • 43
  • 70
0

You should use TypeAdapters for this and then add the TypeAdapter into your gson builder during the object creation.

https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html

Jaron F
  • 151
  • 1
  • 7