Java 如何向 JsonObject 添加新的字段/元素?

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

How to add new Fields/Elements to JsonObject?

javajsoneclipsegson

提问by Lemon Juice

Here is my code. It is an attempt to read JSON using the GSONlibrary.

这是我的代码。这是使用GSON库读取 JSON 的尝试。

 JsonReader reader = new JsonReader( new BufferedReader(new InputStreamReader(s3Object.getObjectContent())) );
reader.beginArray();
int gsonVal = 0;
while (reader.hasNext()) {
       JsonParser  _parser = new JsonParser();
       JsonElement jsonElement =  _parser.parse(reader);
    JsonObject jsonObject1 = jsonElement.getAsJsonObject();
}

Now, I need to add 2 additional fields to this JsonObject. I need to add primary_keyfield and hash_indexfield.

现在,我需要为此添加 2 个附加字段JsonObject。我需要添加primary_key字段和hash_index字段。

I tried the below, but it didn't work.

我尝试了下面的方法,但没有用。

jsonObject1.add("hash_index", hashIndex.toString().trim()); 
jsonObject1.add("primary_key", i); 

When these two values are added, the JsonObject will look like below.

添加这两个值后,JsonObject 将如下所示。

{
        "hash_index": "00102x05h06l0aj0dw",
        "body": "Who's signing up for Obamacare?",
        "_type": "ArticleItem",
        "title": "Who's signing up for Obamacare? - Jan. 13, 2014",
        "source": "money.cnn.com",
        "primary_key": 0,
        "last_crawl_date": "2014-01-14",
        "url": "http://money.cnn.com/2014/01/13/news/economy/obamacare-enrollment/index.html"
    }

How can I do this? This is my first time with GSON.

我怎样才能做到这一点?这是我第一次使用 GSON。

采纳答案by Asif Bhutto

You have to use the JsonObject#addProperty()

你必须使用 JsonObject#addProperty()

 final JsonObject json = new JsonObject();
 json.addProperty("type", "ATP");

In Your case

在你的情况下

jsonObject1.addProperty("hash_index", hashIndex.toString().trim()); 
jsonObject1.addProperty("primary_key", i); 

回答by Anirban Nag 'tintinmj'

You have to use putmethod.

你必须使用put方法。

jsonObject1.put("hash_index", hashIndex.toString().trim()); 
jsonObject1.put("primary_key", i); 

From your comment it's look like you have to use addPropertymethod.

从您的评论看来,您必须使用addProperty方法。

jsonObject1.addProperty("hash_index", hashIndex.toString().trim()); 
jsonObject1.addProperty("primary_key", i);

回答by Lakmal Vithanage

Use put method. jsonObject1.put("hash_index", hashIndex.toString().trim()); jsonObject1.put("primary_key", i);

使用 put 方法。 jsonObject1.put("hash_index", hashIndex.toString().trim()); jsonObject1.put("primary_key", i);