使用gson.toJson序列化嵌套的org.json.JSONObject,将其添加到"map"钥匙 [英] Serializing nested org.json.JSONObject using gson.toJson adding into "map" key

查看:550
本文介绍了使用gson.toJson序列化嵌套的org.json.JSONObject,将其添加到"map"钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到这样的输出JSON

I receive the output JSON as such

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

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

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

我刚刚发现gson在序列化对象内部的数组时还添加了"myArrayList".这非常令人沮丧,并且使得通过JSON进行解析变得困难而烦人.

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

推荐答案

万一有人想知道如何解决此问题,我通过执行以下操作找到了解决方案:

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

这篇关于使用gson.toJson序列化嵌套的org.json.JSONObject,将其添加到"map"钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆