JSONObject inside an object is getting serialized to some other form as compared to a map

555 views Asked by At

Why serialization is not working as expected for the JSONObject inside an Object ?

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

Result produces : {"name":"name", {"empty":false,"mapType":"java.util.HashMap"}}

Expected result : {"name":"name", "json": {"key":"value"}}

How to resolve this behaviour ?

2

There are 2 answers

2
fascynacja On

If you are planning to have only a Map with key values in the "json" field you can try this approach:

Instead of JSONObject keep a Map.

record Random (String name, Map json){}

The code to serialize will use json.toMap()

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

You can create your own Serializer: JSONObjectSerializer and register it in ObjectMapper. Again assumption is that you are planning to have only a Map with key values in the "json" field.

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());
        }
    }
}

This code will produce output:

{"name":"name","json":{"key":"value"}}