How to iterate a JsonObject (gson)

前端 未结 5 1098
有刺的猬
有刺的猬 2021-02-19 08:50

I have a JsonObject e.g

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

Every JsonObject contains

5条回答
  •  爱一瞬间的悲伤
    2021-02-19 09:33

    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 attributes = new HashMap();
            Set> entrySet = jsonObject.entrySet();
            for(Map.Entry entry : entrySet){
              attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
            }
    
            for(Map.Entry 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 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);
        }
    

提交回复
热议问题