Search code examples
javajsongsonjson-deserialization

GSON, disable deserializaton from specific field/variable and save json as string


How to get JSON as string from variable tags after deserializating?

json file as example:

{
"first_name": "John",
"last_name" : "Well",
"tags": {"1001": "author", "1002": "signer"}
}

class Person:

Class Person{
  String first_name;
  String last_name;

  String tags; // here should be json as string
}

Method to calling funciton deseralization json.

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
gson.fromJson(txt, Person.class);

Error:

10-04 07:33:28.035 26156-26481/pl.xxxE/AndroidRuntime: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 4 column 9

** UPDATED 1 **

Answer from @dtx12:

Class Person{
  String first_name;
  String last_name;
  JSONObject tags; // but result {}
}

Also that answer wasn't helpfully because of empty result. But like that should be stopped in deserialization's progress ...I am talking about performance usinng mobile app with deserializating an 1000+ objects.


Solution

  • Use JsonObject instead of String and then call method toString() on this field (you can make getter for this purposes for example)