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

旧城冷巷雨未停 提交于 2019-12-11 16:59:33

问题


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"]}

回答1:


User GsonBuilder create Gson. register custom TypeAdapter

new GsonBuilder()
.registerTypeAdapter(JSONObject.class, JSONObjectAdapter.sInstance)
.registerTypeAdapter(JSONArray.class, JSONArrayAdapter.sInstance)

JSONObjectAdapter.jva

static class JSONObjectAdapter implements JsonSerializer<JSONObject>, JsonDeserializer<JSONObject> {

    public static JSONObjectAdapter sInstance = new JSONObjectAdapter();

    @Override
    public JsonElement serialize(JSONObject src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) {
            return null;
        }

        JsonObject jsonObject = new JsonObject();
        Iterator<String> keys = src.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = src.opt(key);

            JsonElement jsonElement = context.serialize(value, value.getClass());
            jsonObject.add(key, jsonElement);
        }
        return jsonObject;
    }

    @Override
    public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json == null) {
            return null;
        }
        try {
            return new JSONObject(json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            throw new JsonParseException(e);
        }
    }
}

JSONArrayAdapter.java

static class JSONArrayAdapter implements JsonSerializer<JSONArray>, JsonDeserializer<JSONArray> {

    public static final JSONArrayAdapter sInstance = new JSONArrayAdapter();

    @Override
    public JsonElement serialize(JSONArray src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) {
            return null;
        }
        JsonArray jsonArray = new JsonArray();
        for (int i = 0; i < src.length(); i++) {
            Object object = src.opt(i);
            JsonElement jsonElement = context.serialize(object, object.getClass());
            jsonArray.add(jsonElement);
        }
        return jsonArray;
    }

    @Override
    public JSONArray deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json == null) {
            return null;
        }
        try {
            return new JSONArray(json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            throw new JsonParseException(e);
        }
    }
}

look this answer, add custom TypeAdapter




回答2:


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


来源:https://stackoverflow.com/questions/50059808/serializing-nested-org-json-jsonobject-using-gson-tojson-adding-into-map-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!