I need to send a JSON body to REST service. Unfortunately, service is quite old and I need to send a POJO, containing JSON string field. So it looks like this:
class SomeData {
int id;
SomePojo jsonField;
...
}
So SomeData should be sent like this:
{'id': 1, 'jsonField': some_json_string}
I haven't found any Jackson magic annotation to make it works and I've got a doubt it can be made somehow because of type erasure in Java and it may not be possible to write custom serializer for this purpose but I'm not sure.
Could you please suggest any idea of how I can make it work or workaround the issue? Thank you very much in advance!
When you are using Jackson in a Spring context, you can make use of the @JsonSerialize
-Annotation
Assuming you have the Classes from your question, then you can put the above mentioned annotation on your getter:
public class SomeData {
int id;
SomePojo jsonField;
@JsonSerialize(using = PojoSerializer.class)
public SomePojo getJsonField(){
return jsonField;
}
}
Then creating the PojoSerializer
:
public class PojoSerializer extends JsonSerializer<SomePojo>{
@Override
public void serialize( SomePojo pojo, JsonGenerator jsonGenerator, SerializerProvider serializerProvider ) throws IOException{
jsonGenerator.writeString(pojo.getSomeString());
}
}
The rest does spring for you
You need to implement your own serialiser, you can then configure it at ObjectMapper
level, e.g.:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(SomeData.class, new SomeDataSerialiser());
mapper.registerModule(module);
You can find the complete example here.
As asked, I'll post a simple example of org.json
.
Class sample :
import org.json.*;
public class MyClass {
private int id;
private String randomString;
public MyClass(int id_, String randomString_){
this.id = id_;
this.randomString = randomString_;
}
public int getId() {
return id;
}
public String getRandomString() {
return randomString;
}
//Uses the getter to generate a JSon representation of the class
public JSONObject toJson(){
return new JSONObject(this);
}
}
Main :
public static void main(String[] args) {
MyClass test = new MyClass(1, "Test");
System.out.println(test.toJson().toString());
}
Output : {"id":1,"randomString":"Test"}
You can download the Jar here.
You can find the full documentation here.
Also this link for more usage examples.
来源:https://stackoverflow.com/questions/46825695/serializing-a-field-as-json