Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate a JsonObject (gson)

I have a JsonObject e.g

JsonObject jsonObject = {"keyInt":2,"keyString":"val1","id":"0123456"}

Every JsonObject contains a "id" entry, but the number of other key/value pairs is NOT determined, so I want to create create an object with 2 attributes:

class myGenericObject {
  Map<String, Object> attributes;
  String id;
}

So I want my attributes map to look like this:

"keyInt" -> 4711
"keyStr" -> "val1"

I found this solution

Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
  attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
}

but the values are enclosed by ""

"keyInt" -> "4711"
"keyStr" -> ""val1""

How to get the plain values (4711 and "val1")?

Input data:

{
  "id": 0815, 
  "a": "a string",
  "b": 123.4,
  "c": {
    "a": 1,
    "b": true,
    "c": ["a", "b", "c"]
  }
}

or

{
  "id": 4711, 
  "x": false,
  "y": "y?",
}
like image 859
Floyd Avatar asked Jan 15 '15 13:01

Floyd


People also ask

How do I iterate through JSONArray?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

What is JsonElement in Java?

A class representing an element of Json. It could either be a JsonObject , a JsonArray , a JsonPrimitive or a JsonNull .


2 Answers

replace "" with blank.

   Map<String, Object> attributes = new HashMap<String, Object>();
   Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
   for(Map.Entry<String,JsonElement> entry : entrySet){
    if (! nonProperties.contains(entry.getKey())) {
      properties.put(entry.getKey(), jsonObject.get(entry.getKey()).replace("\"",""));
    }
   }
like image 79
atish shimpi Avatar answered Oct 10 '22 07:10

atish shimpi


How are you creating your JsonObject? Your code works for me. Consider this

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
...
...
...
try{
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyInt", 2);
        jsonObject.addProperty("keyString", "val1");
        jsonObject.addProperty("id", "0123456");

        System.out.println("json >>> "+jsonObject);

        Map<String, Object> attributes = new HashMap<String, Object>();
        Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
        for(Map.Entry<String,JsonElement> entry : entrySet){
          attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
        }

        for(Map.Entry<String,Object> att : attributes.entrySet()){
            System.out.println("key >>> "+att.getKey());
            System.out.println("val >>> "+att.getValue());
            } 
    }
    catch (Exception ex){
        System.out.println(ex);
    }

And it is working fine. Now I am interested in knowing how you created that JSON of yours?

You can also try this (JSONObject)

import org.json.JSONObject;
...
...
...
try{
        JSONObject jsonObject = new JSONObject("{\"keyInt\":2,\"keyString\":\"val1\",\"id\":\"0123456\"}");
        System.out.println("JSON :: "+jsonObject.toString());

        Iterator<String> it  =  jsonObject.keys();
         while( it.hasNext() ){
             String key = it.next();
             System.out.println("Key:: !!! >>> "+key);
             Object value = jsonObject.get(key);
             System.out.println("Value Type "+value.getClass().getName());
            }
    }
    catch (Exception ex){
        System.out.println(ex);
    }
like image 20
Syed Mauze Rehan Avatar answered Oct 10 '22 08:10

Syed Mauze Rehan