PeakGen
PeakGen

Reputation: 23025

How to add new Fields/Elements to JsonObject?

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

 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_key field and hash_index field.

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.

{
        "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.

Upvotes: 5

Views: 20908

Answers (3)

You have to use put method.

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

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

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

Upvotes: 0

Asif Bhutto
Asif Bhutto

Reputation: 3994

You have to use the 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); 

Upvotes: 10

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

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

Upvotes: 0

Related Questions