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

Asked

Viewed 611 times

4

I’m developing a dynamic form for Android in which you get a Json file and create the forms. Everything is automated, except for the part where I have to pick up a string in Json’s hand. There is a way to read the string without setting its name inside the .getString?

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

I am using the jo.getString("nome") for example, and placing inside a string vector, I can place it in the vector without knowing if inside the json the string "name"?

1 answer

2

If the structure of Json is always the same can make a Parser using the class Jsonreader.

For the example you posted would be 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:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.