agingcabbage32
agingcabbage32

Reputation: 364

How to write custom json serializer and serialize value as an array

I need to serialize simple java object with three fields (one is a List of objects) into json to look something like this:

{
"id": "1",
"fields": [
    {
        "value": {
                "someNumber": "0.0.2"
            },
        "id": "67"
    }
],
"name": "Daniel"}

I've read guides on custom serializers StdSerializer and JsonGenerator, as i undestood, to write "name": "Daniel" into json you need to do somwthing like gen.writeObjectField("name", name); but i cannot get my head on two things:

  1. How to write some string value like here:

        "value": {
          "name": "0.0.2"
        },
    
  2. And how to write java List as an array like this:

    "fields": [
    {
        "value": {
                "someNumber": "0.0.2"
            },
        "id": "67"
    }]
    

where "fields" is an List full of objects having two fields: "value" and "id". Any help is appreciated

Upvotes: 0

Views: 1084

Answers (1)

zzzzzhangyanqiu
zzzzzhangyanqiu

Reputation: 96

like this


public class Test {
    public static void main(String[] args) throws IOException {
        String ret;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ObjectMapper mapper = new ObjectMapper();
        JsonGenerator jg = mapper.getJsonFactory().createJsonGenerator(new PrintWriter(bos));

        jg.writeStartObject();

        jg.writeStringField("id", "1");

        jg.writeArrayFieldStart("fields");

        jg.writeStartObject();
        jg.writeObjectFieldStart("value");
        jg.writeStringField("someNumber","0.0.2");
        jg.writeEndObject();
        jg.writeStringField("id","67");
        jg.writeEndObject();

        //you can write more objects in fields here
        jg.writeEndArray();

        jg.writeStringField("name","Daniel");

        jg.writeEndObject();

        jg.flush();
        jg.close();

        ret = bos.toString();
        bos.close();
        System.out.println(ret);

    }
}

and the result is

{
    "id":"1",
    "fields":[
        {
            "value":{
                "someNumber":"0.0.2"
            },
            "id":"67"
        }
    ],
    "name":"Daniel"
}

Upvotes: 1

Related Questions