I have created a custom serializer for my java class, Which contains the many nested objects.
My motive is to add the type of the java class in the serialized JSON object.
ex My class type is Student and JSON created is
{ id:1, name:abc }
I want to have it as
{id:1, name:abc, type:"Student "}
which is not that difficult. My issue is that my object is like
{
"description": null,
"edit": [],
"strategy": [
{
"description": null,
"regions": {
"region": []
},
"markets": {
"market": [
{},
{}
]
},
"securityTypes": {},
"parameter": [
{
"description": null,
"enumPair": [],
"name": "StartTime",
"fixTag": 7602,
"use": "REQUIRED",
"mutableOnCxlRpl": true,
"revertOnCxlRpl": null,
"definedByFIX": false,
"minValue": null,
"maxValue": null,
"constValue": null,
"localMktTz": null
},
{},
{},
{}
],
"edit": []
}
],
"draftFlagIdentifierTag": null,
"changeStrategyOnCxlRpl": null,
"imageLocation": null
}
and I want to add type to every parameter and rest all the things should be kept as normal serialized.
What I tried is
public class StrategiesSerializer extends StdSerializer<StrategiesT> {
public StrategiesSerializer() {
this(null);
}
public StrategiesSerializer(Class<StrategiesT> strategies) {
super(strategies);
}
@Override
public void serialize(StrategiesT value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
for(Field field: value.getClass().getDeclaredFields()) {
System.out.println(field.getName());
if(field.getName() != "strategy") provider.defaultSerializeField(field.getName(), field, gen);
if(field.getName() == "strategy"){
gen.writeArrayFieldStart("strategy");
for(StrategyT strategy : value.getStrategy()) {
for(Field strategyField : strategy.getClass().getDeclaredFields()) {
provider.defaultSerializeField(strategyField.getName(), strategyField, gen);
}
gen.writeStartObject();
gen.writeStringField("type", strategy.getClass().getName());
gen.writeEndObject();
}
gen.writeEndArray();
}
}
gen.writeEndObject();
}
}
This gives me some result which is not correct.
Please let me know if i can make myself more clear.