I have very complex JSON with many nested fields coming from backend, example,
{
"a": ...
"b": ...
"not-required-1":{
"not-required-2":[
...
]
..
},
"not-required-3":{
"not-required-4":[
...
]
...
}
}
I am only interested in "a" and "b" and I can map to corresponding types for the values. But object has many fields which I don't need but they should serialize when I make changes in "a" and "b".
If I only create type with "a" and "b", when I serialize my object, all "not-required" fields are gone. The only option is to map every field in not-required to corresponding Java class, but they fall in number of 100s.
Clarification,
Backend sends JSON, which is processed in my code and I need to send JSON back to backend.. though I don't need to process all the fields, doesn't mean backend doesn't need them.
I want to convert incoming JSON to POJO and use it through out the app, and serialize it back to JSON using GSON.
C#'s JSON.NET library has support for hybird object serialization using Json.Linq.
c# example.
class DataObject{
[JsonProperty("a")]
DataA A {get;set;}
[JsonProperty("b")]
DataB B {get;set;}
[JsonProperty("not-required-a")]
Json.Linq.JsonElement NotRequiredA {get;set;}
[JsonProperty("not-required-b")]
Json.Linq.JsonElement NotRequiredB; {get;set;}
}
In C# this way I don't need to map fields of NotRequiredA and NotRequiredB, but they will serialize correctly when needed.
You can use JsonElement. For example:
class DataObject{
@Expose @Serialize("a")
DataA A;
@Expose @Serialize("b")
DataB B;
@Expose @Serialize("not-required-a")
JsonElement NotRequired;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With