Reputation: 561
Context: I'm working on a middle-man service that acts like a CMS system. I get a full complex json file dropped on my server which I then need to serve out to my clients that expect json content. (let's ignore the validation part for now)
I have a name, version and content fields that exist at the top level. Content (chapters) exists as an array of nested complex objects (~5 levels deep).
{
"name": "MyCourse",
"version": 12345,
"chapters": [
{
"name": "Chapter01",
"content": {
"menu": {
"id": "Chapter01_EndMenu",
"file": "ch1_end_op.wav"
},
"score": {
"id": "Chapter01_Score",
"files": [....
What I've tried (and works): Building out my pojo to mirror the json structure where content(chapters) exists as a list of complex objects. Calling gson parser on this works.
What I'm trying to do: Have a simpler pojo with just name, version and content where content just stores the array representation (chapters and nested objects) as a String.
I tried defining my content field in pojo as a String and set the @SerializedName annotation to force gson to parse the array as a string into it but that doesn't work.
Is it possible to partially get the json as fields and get the rest (of the nested array) into a string field in my pojo?
Upvotes: 0
Views: 5815
Reputation: 8368
You can define your own adapter for String data-type.
E. g. :
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(String.class, new JsonDeserializer<String>() {
public String deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return json.toString();
}
});
Gson gson = builder.create();
Now it can store chapters data as String.
Upvotes: 0
Reputation: 2052
It's simple in JSONObject
you can get the JSON String as it is using the keys.
String jsonString = "{ \"name\": \"MyCourse\", \"version\": 12345, \"chapters\": [ { \"name\": \"Chapter01\"}]}";
JSONObject jsonObject = new JSONObject(jsonString);
Details details = new Details();
details.setName(jsonObject.get("name"));
details.setVersion(jsonObject.get("version"));
details.setChapters(jsonObject.get("chapters"));
You can try this.
Upvotes: 2