String for Array / List

1

I have the following String:

[{"Monstro":"Lobo","HP":100,"Level":2},{"Level":"1","HP":"100","Monstro":"Bruxa"}]

You need to put it inside a Array ou List to get the values of each monster.

  • How do I do this?

Sorry if the question seems obvious.

OBS : These are JSON data that are within […] f% of the way it is and has },{ 2 different values that are within [...] .

    
asked by anonymous 02.12.2017 / 01:12

1 answer

1

I would follow the same idea as Francisco's comment , I created an object that mapped the attributes of the monster: nome , hitpoints and level , even though I would not use them by the hour in my application. But if the goal is just to get all the values of the key Monstro , you can do this:

public final List<String> getMonstros(String json){
    List<String> monsters = new ArrayList<>();
    try {
        new JSONArray(json).forEach(item -> {

            JSONObject object = (JSONObject) item;
            if(object.has("Monstro"))
                monsters.add(object.getString("Monstro"));

        });  
    } catch(Exception ex){
        // Tratamento de exceção.
    }
    return monsters;
}
final String json = "[{\"Monstro\":\"Lobo\",\"HP\":100,\"Level\":2}, {\"Level\":\"1\",\"HP\":\"100\",\"Monstro\":\"Bruxu\"}]";
System.out.println(getMonstros(json)); // [Lobo, Bruxu]
    
02.12.2017 / 01:48