How to read a Json without knowing what's inside it or the amount of data?

4

I am developing a dynamic form for Android in which you receive a Json file and create the forms. It's all automated, except for the part that I have to get a string in Json's hand. Is there a way to read the string without naming it within .getString ?

"{\"nome\":\"nome\",\"sobrenome\":\"sobrenome\",\"idade\":\"idade\",\"endereco\"‌​:\"endereco\",\"pais\":\"pais\"}"

I'm using jo.getString("nome") for example, and putting inside a string vector, how do I put it in the vector without knowing if inside the json there would be the string "name"?

    
asked by anonymous 16.06.2015 / 23:16

1 answer

2

If the Json structure is always the same you can do a Parser using the JsonReader .

For the example you posted it would look like this:

public ArrayList<String> getValuesFromJson(String jsonString) throws IOException {
    ArrayList<String> values = new ArrayList<String>();
    InputStream stream = new ByteArrayInputStream(jsonString.getBytes(Charset.forName("UTF-8")));
    JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
    reader.beginObject();
    while (reader.hasNext()) {
        reader.nextName();
        String value = reader.nextString();
        values.add(value);
    }
    return values;
}

To use use:

    String jsonString = "{\"nome\":\"Paulo\",\"sobrenome\":\"Sousa\",\"idade\":\"25\"}";
    ArrayList<String> lista;
    try {
        lista = getValuesFromJson(jsonString);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
17.06.2015 / 16:11