How to transform Json into an object with dynamic fields using Gson on Android?

Asked

Viewed 565 times

2

I have the following json:

{"Data" :{ "Description": "app", "Campo2": "app2", "Campo3": "app3"}, "Instring" : "1", "Token" : "Zoebarw9nimk9o"}

The "Date" field may contain 1:N fields.

To illustrate, I tried to assemble the following class structure:

class JsonDynamicData {
        Map<String, String> info;
    }

    class JsonDynamicClass {

        JsonDynamicData Data;
        int inString;
        String token;           

        public JsonDynamicClass() {
            Data = new JsonDynamicData();
        }
    }

    private void jsonDinamico() {
        //TODO
        try {

            String json = IOUtils.toString(getActivity().getResources().openRawResource(R.raw.jsonmoredata));

            JsonDynamicClass toJson = new Gson().fromJson(json, JsonDynamicClass.class);                

        } catch (IOException e) {
        }
    }

However the conversion of Json to my object did not work.

How should I proceed to create an object structure where the "Date" field can receive 1:N fields?

1 answer

4


It is necessary to use Gson?

Because Android has the Jsonobject, that already does something similar to what you want, transforming the string JSON, in a tuple object, you can do something similar to this:

String str = "{'nome': 'Fernando', 'idade': 25}";
JSONObject json;
try {
    json = new JSONObject(str);
    int idade = json.getInt("idade");
    String nome = json.getString("nome");
} catch (JSONException e) {
    e.printStackTrace();
}

The Gson, Google, is great, to use when your JSON, corresponds to a class model of your project, as it manages to do all this conversion for you. In your case it seems to me more appropriate to use the Jsonobject even.

Browser other questions tagged

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