jackson 与Map相比,对象内部的JSONObject被序列化为其他形式

nhaq1z21  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(158)

为什么序列化在对象内部的JSONObject没有按预期工作?

class Random {
    String name;
    JSONObject json;
}
JSONObject json= new JSONObject();
json.put("key", "value");
Random random = new Random("name", json);
new ObjectMapper().writeValueAsString(); ->

结果产生:{"name":"name", {"empty":false,"mapType":"java.util.HashMap"}}
预期结果:{"name":"name", "json": {"key":"value"}}

如何解决这种行为?

f5emj3cl

f5emj3cl1#

您可以创建自己的序列化程序:JSONObjectSerializer并在ObjectMapper中注册它。再次假设您计划只使用“json”字段中具有键值的Map。

record Random(String name, JSONObject json) {}

public class SerializerExample {

    public static void main(String[] args) throws JsonProcessingException {

        JSONObject json = new JSONObject();
        json.put("key", "value");
        Random random = new Random("name", json);
        
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(JSONObject.class, new JSONObjectSerializer());
        mapper.registerModule(module);
        
        String s = mapper.writeValueAsString(random);
        System.out.println(s);
    }

    public static class JSONObjectSerializer extends StdSerializer<JSONObject> {

        public JSONObjectSerializer() {
            this(null);
        }

        public JSONObjectSerializer(Class<JSONObject> t) {
            super(t);
        }

        @Override
        public void serialize(
            JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeObject(value.toMap());
        }
    }
}

这段代码将产生输出:
{“name”:“name”,“json”:{“key”:“value”}}

n1bvdmb6

n1bvdmb62#

如果你计划只在Map中的“json”字段中包含键值,你可以尝试这种方法:
而不是JSONObject保持一个Map。

record Random (String name, Map json){}

序列化的代码将使用json.toMap()

JSONObject json = new JSONObject();
json.put("key", "value");
Random random = new Random("name", json.toMap());
String s = new ObjectMapper().writeValueAsString(random);

相关问题