Use class name as root key for JSON Jackson serialization

前端 未结 11 2789
长情又很酷
长情又很酷 2020-11-27 18:05

Suppose I have a pojo:

import org.codehaus.jackson.map.*;

public class MyPojo {
    int id;
    public int getId()
    { return this.id; }

    public void          


        
11条回答
  •  清歌不尽
    2020-11-27 18:34

    Below is a way to achieve this

    Map singletonMap = Collections.singletonMap("mypojo", mp);
    System.out.println(mapper.writeValueAsString(singletonMap));
    

    Output { "mypojo" : { "id" : 4}}

    Here the advantage is that we can give our on name for the root key of json object. By the above code, mypojo will be the root key. This approach will be most useful when we use java script template like Mustache.js for iteration of json objects

提交回复
热议问题