Serializing a field as json

扶醉桌前 提交于 2019-12-31 02:19:19

问题


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!


回答1:


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




回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!