user591124
user591124

Reputation: 503

gson and json deserializing

This is the json encoding my php echos:

{"detail1":{"key1":"value1","key2":"value2","key3":"value3"},"detail2":["elementone","elementtwo","elementthree"],"detail3":["element1","element2","element3"]}

The gson commands i use in the application are:

Gson gson = new Gson();
ParseActivity.parsedata = gson.fromJson(result, new TypeToken < HashMap < String , Object>>(){}.getType());

But gson is giving a jsonparseexception and is not able to parse, parsedata is a static variable of the same type.

Thanks for any help

Upvotes: 1

Views: 1031

Answers (1)

BalusC
BalusC

Reputation: 1109645

You need to be more explicit in the returned type. The field detail1 is a Map<String, String> and other fields are List<String>. You need to create a wrapper class (a Javabean) with exactly those fields:

public class Details {
    private Map<String, String> detail1;
    private List<String> detail2;
    private List<String> detail3;

    // Add/generate getters/setters.
}

so that you can use it as follows:

Details details = new Gson().fromJson(result, Details.class);

Alternatively, you can let Gson convert it to a JsonElement tree so that you can traverse it manually:

JsonElement details = new Gson().toJsonTree(result);

Upvotes: 3

Related Questions