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

时间:2018-04-27 09:53:02

标签: java json gson fasterxml

在我的代码中,我需要将org.json.JSONObject添加到使用gson.toJson序列化的另一个对象。但是,当序列化此对象时,JSONObject中的值将由gson本身嵌套到映射键中。例如,

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

我收到输出JSON

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

我需要知道如何避免gson解析器自动添加的map键。

编辑:我刚刚发现gson在序列化对象内部的数组时也会添加"myArrayList"。这非常令人沮丧,使得通过JSON解析变得困难和烦人。

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

3 个答案:

答案 0 :(得分:1)

用户GsonBuilder创建Gson。注册自定义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

答案 1 :(得分:1)

尝试使用com.google.gson.JsonObject而不是JSONObject。请参阅this

答案 2 :(得分:0)

如果有人想知道如何解决这个问题,我通过以下方式找到了解决方案:

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