简体   繁体   English

使用添加到“map”键的 gson.toJson 序列化嵌套的 org.json.JSONObject

[英]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 .在我的代码中,我需要将一个org.json.JSONObject添加到另一个使用gson.toJson序列化的对象。 However, when this object is serialized, the values in the JSONObject are nested into a map key by gson itself.然而,当这个对象被序列化时, JSONObject中的值被 gson 本身嵌套到一个映射键中。 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我收到这样的输出 JSON

{"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.我需要知道如何避免 gson 解析器自动添加的map键。

Edit: I just discovered that gson also adds a "myArrayList" when it serializes an array inside the object.编辑:我刚刚发现 gson 在序列化对象内的数组时还会添加一个"myArrayList" This is extremely frustrating and makes parsing through the JSON difficult and annoying.这非常令人沮丧,并使解析 JSON 变得困难和烦人。

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

User GsonBuilder create Gson.用户 GsonBuilder 创建 Gson。 register custom TypeAdapter注册自定义 TypeAdapter

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

JSONObjectAdapter.jva 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 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 看看这个答案,添加自定义 TypeAdapter

Try to use com.google.gson.JsonObject rather than JSONObject .尝试使用com.google.gson.JsonObject而不是JSONObject Please see this .请看这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM