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

2

I have the following json:

  

{"Description": "app", "Field2": "app2", "Field3": "app3"}, "InString": "1", "Token": "ZoebarW9NiMk9O"}

The "Data" field can contain 1: N fields.

For example, I tried to build 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 Json's conversion to my object did not work.

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

    
asked by anonymous 27.06.2014 / 15:41

1 answer

4

Do you need to use Gson ?

Because Android has JSONObject , which already does something similar to what you want, transforming the string JSON into a tuples 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();
}

Google's Gson is great to use when your JSON , corresponds to a class of your project template, since it can do all this conversion for you. In your case, I think it's more appropriate to use JSONObject .

    
27.06.2014 / 15:54