如何在 Java 中使用 GSON 将 JSON 对象的映射转换为 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21247998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:39:23  来源:igfitidea点击:

How to convert map of JSON objects to JSON using GSON in Java?

javajsonhashmapgson

提问by Prod Tester

I have a map of JSON objects as follows:

我有一个 JSON 对象的映射如下:

Map<String,Object> map = HashMap<String,Object>();
map.put("first_name", "prod");
JSONObject jsonObj = new JSONObject("some complex json string here");
map.put("data", jsonObj);

Gson gson = new Gson();
String result = gson.toJson(map);

Now if the "some complex JSON string here" was:

现在,如果“这里有一些复杂的 JSON 字符串”是:

{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }

and execute above code gives me something like:

并执行上面的代码给了我类似的东西:

{
    "first_name": "prod",
    "data": {
        "map": {
            "sender": {
                "map": {
                    "id": "test test"
                    }
                }
            },
            "recipients": {
                "map": {
                    "id": "test1 test1"
                }
            }
        }
    }
}

I might have some syntax error up there, but basically I don't know why I am seeing objects wrapped around map's.

我可能有一些语法错误,但基本上我不知道为什么我看到围绕map's 的对象。

Update

更新

according to comments, it is a bad idea to mix different json parsers. i can understand that. but my case requires calling an external api which takes a hash map of objects that are deserialized using gson eventually.

根据评论,混合不同的 json 解析器是一个坏主意。我能理解。但我的情况需要调用一个外部 api,它需要一个最终使用 gson 反序列化的对象的哈希映射。

is there any other object bedsides JSONObject that i can add to the map and still have gson create json out of it without extra 'map' structure? i do understand that i can create java beans and achieve this. but i'm looking for a simpler way since my data structure can be complex.

是否有任何其他对象床边 JSONObject 可以添加到地图中,并且仍然让 gson 在没有额外的“地图”结构的情况下从中创建 json?我知道我可以创建 java bean 并实现这一点。但我正在寻找一种更简单的方法,因为我的数据结构可能很复杂。

Update2

更新2

going one step back, i am given a xml string. and i have converted them to json object. now i have to use an external api that takes a map which in turn gets converted to json string using gson in external service.

退一步,我得到了一个 xml 字符串。我已将它们转换为 json 对象。现在我必须使用一个外部 api,它需要一个地图,然后在外部服务中使用 gson 将地图转换为 json 字符串。

so i am given an xml data structure, but i need to pass a map to that function. the way i have described above produces extra 'map' structures when converted to json string using gson. i do not have control to change how the external service behaves (e.g. using gson to convert the map).

所以我得到了一个 xml 数据结构,但我需要将映射传递给该函数。当使用 gson 转换为 json 字符串时,我上面描述的方式会产生额外的“地图”结构。我无法控制更改外部服务的行为方式(例如使用 gson 转换地图)。

采纳答案by Brian Roach

Mixing classes from two different JSON libraries will end in nothing but tears. And that's your issue; JSONObjectis not part of Gson. In addition, trying to mix Java data structures with a library's parse tree representations is also a bad idea; conceptually an object in JSON isa map.

混合来自两个不同 JSON 库的类只会让人流泪。这就是你的问题;JSONObject不是 Gson 的一部分。此外,尝试将 Java 数据结构与库的解析树表示混合也是一个坏主意;从概念上讲,JSON 中的对象地图。

If you're going to use Gson, either use all Java objects and let Gson convert them, or use the classes from Gson:

如果您要使用 Gson,请使用所有 Java 对象并让 Gson 转换它们,或者使用 Gson 中的类:

JsonObject root = new JsonObject();
root.addProperty("first_name", "prod");

JsonElement element = new JsonParser().parse(complexJsonString);
root.addProperty("data", element);

String json = new Gson().toJson(root);

回答by Sotirios Delimanolis

This has to do with the internal implementation of JSONObject. The class itself has an instance field of type java.util.Mapwith the name map.

这与JSONObject. 类本身有一个类型java.util.Map为 name的实例字段map

When you parse the String

当你解析 String

{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }

with JSONObject, you actually have 1 root JSONObject, two nested JSONObjects, one with name senderand one with name recipients.

with JSONObject,您实际上有 1 个 root JSONObject,两个嵌套的JSONObjects,一个带有 name sender,另一个带有 name recipients

The hierarchy is basically like so

层次结构基本上是这样

JSONObject.map ->
    "sender" -> 
            JSONObject.map ->
                    "id" -> "test test",
    "recipients" ->
            JSONObject.map ->
                    "id" -> "test test1"

Gson serializes your objects by mapping each field value to the field name.

Gson 通过将每个字段值映射到字段名称来序列化您的对象。



Listen to this man.

And this one.

听听这个人的话。

和这个。

回答by dlao

I'd a similar problem and I finally resolved it using json-simple.

我有一个类似的问题,我最终使用json-simple解决了它。

HashMap<String, Object> object = new HashMap<String,Object>;

// Add some values ...

// And finally convert it
String objectStr = JSONValue.toJSONString(object);

回答by user2845946

You may try out the standard implementation of the Java API for JSON processingwhich is part of J2EE.

您可以尝试用于 JSON 处理Java API的标准实现,它是J2EE 的一部分。

JsonObject obj = Json
    .createObjectBuilder()
    .add("first_name", "prod")
    .add("data", Json.createObjectBuilder()
    .add("sender", Json.createObjectBuilder().add("id", "test test"))
    .add("recipients", Json.createObjectBuilder().add("id", "test1 test1"))).build();

Map<String, Object> prop = new HashMap<String, Object>() {
    {
        put(JsonGenerator.PRETTY_PRINTING, true);
    }
};
JsonWriter writer = Json.createWriterFactory(prop).createWriter(System.out);
writer.writeObject(obj);
writer.close();

The output should be:

输出应该是:

{
    "first_name":"prod",
    "data":{
        "sender":{
            "id":"test test"
        },
        "recipients":{
            "id":"test1 test1"
        }
    }
}