简体   繁体   中英

iterate a List<HashMap<String, String>> values using java

I have a json response like this

{
  "queryPath": "/api/",
  "nId": "f084f5ad24fcfaa9e9faea0",
  "statusCode": 707
  "statusMessage": "Success",
  "results": {
    "data": [
      {
        "id": "10248522500798",
        "capabilities": [
          "men",
          "women"
        ],
        "name": "errt2"
      },
      {
        "id": "418143778",
        "capabilities": [
          "dog",
          "cat"
        ],
        "name": "Livin"
      }
    ]
  }
}

Here am adding results.data to a list as follows

  private List<HashMap<String, String>> episodes = new ArrayList<HashMap<String, String>>();
  episodes =helper.getJSONValue(response, "results.data"); 



   public <T>T getJSONValue(Response res, String path ){
        String json = res.asString();
        JsonPath jpath = new JsonPath(json);
        return jpath.get(path);
    }

so episodes contains all data i mean all results.data While i debuging am getting this way

 [{id=10248522500798, name=errt2, capabilities=[men, women]}, {id=418143778, name=Livin, capabilities=[dog, cat]}]

Here i have capabilities [men, women] and [dog, cat] .i need to check capability contains men or dog. How can i do that?

If i were you i haven't done this.. Use gson and map your json into a java model. It's way better. Afterwards you can access all your model parts with getters and setters.

 MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

As you see it's very simple :)

But if you want to iterate a list that contains a map you can use code block below:

List<Map<String, String>> test = new ArrayList<Map<String, String>>();
        for( Map<String, String> map : test ){
            for( Entry<String, String> entry : map.entrySet() ){
                System.out.println( entry.getKey() + " : " + entry.getValue() );
            }
        }

With the code above you can get all the entry's keys and values and check them.

Edit:

You have to change your List to List<Map<String,Object>> after that:

 List<Map<String, Object>> test = new ArrayList<Map<String, Object>>();
        for( Map<String, Object> map : test ){
            for( Entry<String, Object> entry : map.entrySet() ){
                if( entry.getKey().equalsIgnoreCase( "capabilities" ) ){
                    List<String> myCapabilities = ( List )entry.getValue();
                    if( myCapabilities.contains( "dog" ) && myCapabilities.contains( "cat" ) ){
                        // BLA BLA
                    }
                }
            }
        }

It's a nasty way.. I recommend you to use gson..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM