如果我无法使用注解JsonTypeInfo标记该类,如何为该类自定义JSON包装键?

时间:2018-10-29 12:50:01

标签: java json jackson wrapper

我有这样的代码:

import org.codehaus.jackson.map.*;

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

    public void setId(int id)
    { this.id = id; }

    public static void main(String[] args) throws Exception {
        MyPojo mp = new MyPojo();
        mp.setId(4);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);        
        System.out.println(mapper.writeValueAsString(mp));
    }
}

它可以正常工作:

{"MyPojo":{"id":4}}

但是我想自定义该名称。我无法将MyPojo标记为@JsonTypeInfo,因为我从图书馆学习了这个课程。

在杰克逊市,有办法吗?

2 个答案:

答案 0 :(得分:2)

您也可以将ObjectWriter专门用于此类:

MyPojo mp = new MyPojo();
mp.setId(4);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withRootName("TestPojo");
System.out.println(writer.writeValueAsString(mp));

答案 1 :(得分:0)

代替使用var multi_array = []; var array_a = [2,3,4,1,5]; //1,2,3,4,5 0:1,1:2,2:3,3:0,4:4 var array_b = [0,7,9,8,6]; //8,0,7,9,6 var array_c = ['A','D','B','A','E']; multi_array = [array_a, array_b, array_c]; // clone the first array_a var multi_temp = multi_array[0].slice(0); // sort the clone multi_temp.sort(function(a,b){ if(isNaN(a) || isNaN(b)){ return a > b ? 1 : -1; } return a - b; }); // get the algorithm of key for sorting var id = []; multi_array[0].forEach((val, i) => { id[i] = multi_temp.indexOf(val); } ); // and apply the algorithm in the multi_array multi_array = multi_array.map(item => { var temp = []; id.forEach((val, i) => { temp[val] = item[i]; }); return temp; }); console.log(multi_array);,您可以像这样创建一个新类:

SerializationConfig.Feature.WRAP_ROOT_VALUE

如果您使用此类型的对象创建JSON,则该属性将具有名称​​ myName ,例如:public class MyWrapper { private MyPojo myName = new MyPojo(); public void setId(int id) { myName.setId(id); } }