Java 使用 Gson 添加现有的 json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20522550/
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 02:31:48  来源:igfitidea点击:

Adding an existing json string with Gson

javajsongson

提问by Martin Wickman

I have a String object containing some arbitrary json. I want to wrap it inside another json object, like this:

我有一个包含一些任意 json 的 String 对象。我想将它包装在另一个 json 对象中,如下所示:

{
   version: 1,
   content: >>arbitrary_json_string_object<<
}

How can I reliably add my json string as an attribute to it without having to build it manually (ie avoiding tedious string concatenation)?

如何可靠地将我的 json 字符串作为属性添加到它,而不必手动构建它(即避免繁琐的字符串连接)?

class Wrapper {
   int version = 1;
}

gson.toJson(new Wrapper())
// Then what?

Note that the added json should notbe escaped, but a be part of the wrapper as a valid json entity, like this:

请注意,新增JSON应该没有进行转义,但包装作为一个有效的JSON实体,像这样的BE部分:

{
   version: 1,
   content: ["the content", {name:"from the String"}, "object"]
}

given

给予

String arbitraryJson = "[\"the content\", {name:\"from the String\"}, \"object\"]";

采纳答案by giampaolo

This is my solution:

这是我的解决方案:

  Gson gson = new Gson();
  Object object = gson.fromJson(arbitraryJson, Object.class);

  Wrapper w = new Wrapper();
  w.content = object;

  System.out.println(gson.toJson(w));

where I changed your Wrapperclass in:

Wrapper在哪里改变了你的课程:

// setter and getters omitted
public class Wrapper {
  public int version = 1;
  public Object content;
}

You can also write a custom serializer for your Wrapperif you want to hide the details of the deserialization/serialization.

Wrapper如果您想隐藏反序列化/序列化的详细信息,您还可以为您编写自定义序列化程序。

回答by jwueller

You will need to deserialize it first, then add it to your structure and re-serialize the whole thing. Otherwise, the wrapper will just contain the wrapped JSON in a fully escaped string.

您需要先反序列化它,然后将其添加到您的结构中并重新序列化整个内容。否则,包装器将仅在完全转义的字符串中包含包装的 JSON。

This is assuming you have the following in a string:

这是假设您在字符串中有以下内容:

{"foo": "bar"}

and want it wrapped in your Wrapperobject, resulting in a JSON that looks like this:

并希望它包含在您的Wrapper对象中,从而生成如下所示的 JSON:

{
    "version": 1,
    "content": {"foo": "bar"}
}

If you did not deserialize first, it would result in the following:

如果您没有先反序列化,则会导致以下结果:

{
    "version": 1,
    "content": "{\"foo\": \"bar\"}"
}

回答by Sotirios Delimanolis

Simple, convert your bean to a JsonObjectand add a property.

简单,将您的 bean 转换为 aJsonObject并添加一个属性。

Gson gson = new Gson();
JsonObject object = (JsonObject) gson.toJsonTree(new Wrapper());
object.addProperty("content", "arbitrary_json_string");
System.out.println(object);

prints

印刷

{"version":1,"content":"arbitrary_json_string"}

回答by everton

If you don't care about the whole JSON structure, you don't need to use a wrapper. You can deserialize it to a generic json object, and also add new elements after that.

如果您不关心整个 JSON 结构,则不需要使用包装器。您可以将其反序列化为通用的 json 对象,并在此之后添加新元素。

JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(jsonStr).getAsJsonObject();
obj.get("version"); // Version field

回答by T.K.

For those venturing on this topic, consider this.

对于那些在这个主题上冒险的人,请考虑这个

A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);