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.

1
  • What about? "{\"someField1\":\"someValue1\",\"someField2\":\"someValue2\"}" Commented Dec 18, 2017 at 19:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

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.