Serializing a field as json

淺唱寂寞╮ 提交于 2019-12-01 22:43:08

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.

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