Reputation: 1901
I have following json
:
{
"id": 1,
"title": "Title blabla",
"thing": {
"field1": 1,
"field2": "field2",
"etc": "etc.."
}
}
and model
public class MyModel {
private int id;
private String title;
private String thing;
}
I parse it with gson
Gson gson = new Gson();
MyModel myModel = gson.fromJson(json, type);
and want achieve result:
myModel.id -> 1
myModel.title -> "Title blabla"
myModel.thing-> "{
"field1": 1,
"field2": "field2",
"etc": "etc.."
}"
In other words I do not want some fields to be deserialized, but left as the original coresponding json
strings.
How to achieve this using gson
?
Upvotes: 1
Views: 565
Reputation: 1261
You could change String to Object so that it de-/serializes to the same JSON String. Could look like that:
import com.google.gson.Gson;
public class Answers {
public static void main(String[] args) {
String json = "{"
+ " \"id\": 1,"
+ " \"title\": \"Title blabla\"," + " \"thing\": {"
+ " \"field1\": 1," + " \"field2\": \"field2\","
+ " \"etc\": \"etc..\"" + " }"
+ "}";
Gson gson = new Gson();
MyModel myModel = (MyModel) gson.fromJson(json, MyModel.class);
System.out.println(gson.toJson(myModel));
}
class MyModel {
private int id;
private String title;
private Object thing;
}
}
Output:
{"id":1,"title":"Title blabla","thing":{"field1":1.0,"field2":"field2","etc":"etc.."}}
Upvotes: 1
Reputation: 8580
You can implement your own serializer and desirializer, see here for example.
Upvotes: 2
Reputation: 15052
You could change thing to a Map and then toString() that to produce the results you're looking for.
Upvotes: 2
Reputation: 1077
You have to use an inner class if you want to parse a similar JSON object, try this for example :
public class MyModel {
private int id;
private String title;
private String thing;
public static class thing
{
private string field1;
private string field2;
etc etc
}
}
Upvotes: 1