Search code examples
javajsongsonfasterxml

Serializing nested org.json.JSONObject using gson.toJson adding into "map" key


In my code, I need to add an org.json.JSONObject to another object which is serialized using gson.toJson. However, when this object is serialized, the values in the JSONObject are nested into a map key by gson itself. For example,

public class New {

private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();

public static void something(User user) throws Exception {
    try {
        ObjectWriter ow = new ObjectMapper().writer();
        String json = ow.writeValueAsString(user);
        JSONObject maskedUser = new JSONObject(json);
        Nesting testing = new Nesting(maskedUser, "someting");
        String something  = gson.toJson(testing);
        System.out.println(something);

    } catch (Exception e) {
        throw e;
    }
}

public static void main(String[] args) throws Exception {
    User user = new User("a", "b", "c");
    something(user);
    }
}

I receive the output JSON as such

{"details":{"map":{"lastname":"b","firstname":"a","password":"c"}},"sometim":"someting"}

I need to know how to avoid the map key that gson parser adds automatically.

Edit: I just discovered that gson also adds a "myArrayList" when it serializes an array inside the object. This is extremely frustrating and makes parsing through the JSON difficult and annoying.

"map":{"fruits":{"myArrayList":["Apples"]}

Solution

  • In case anyone is wondering how to fix this, I found the solution by doing the following:

    public static void something(User user) throws Exception {
        try {
            ObjectWriter ow = new ObjectMapper().writer();
            String json = ow.writeValueAsString(user);
            Nesting testing = new Nesting(null, "someting");
            Object object = gson.fromJson(json, Object.class);
            testing.setDetails(object);
            JsonElement something  = gson.toJsonTree(testing);
            System.out.println(something);
    
        } catch (Exception e) {
            throw e;
        }
    }