JSON serialization of JS objects with Spring.
Problem: pass JS object from spring MVC enabled backend to HTML page, use eval (...) on object and invoke function that have been passed from backend.
Solution: By default Spring framework is using Jackson to serialize Java objects. During that serialization all members are passed as strings, while we'd like to have data structure as following:
Done. use eval on front end to convert JSON into actual JS object and enjoy.
Problem: pass JS object from spring MVC enabled backend to HTML page, use eval (...) on object and invoke function that have been passed from backend.
Solution: By default Spring framework is using Jackson to serialize Java objects. During that serialization all members are passed as strings, while we'd like to have data structure as following:
{with such an object it would be possible to do the following to invoke function:
member1 : "value1",
action : function() {
...
}
}
obj.action()In order to do that one would have to implement custom serializer class
public class MySerializer extends JsonSerializer<MyTO> {
public void serialize(MyTO value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField("member1", value.getMember1());
jgen.writeFieldName("action");
jgen.writeRaw(":" + value.getAction());
}
}
Done. use eval on front end to convert JSON into actual JS object and enjoy.
No comments:
Post a Comment