Gson usage : formJson

avoid to face the exception ‘java.lang.ClassCastException With com.google.gson.internal.LinkedTreeMap cannot be cast to…’, we use the TypeToken to convert json to List

public class Object {
    @SerializedName("n")
    private String name;
    @SerializedName("i")
    private String id;

    public String getName() {
        return name;
    }

    public Object setName(String name) {
        this.name = name;
        return this;
    }

    public String getId() {
        return id;
    }

    public Object setId(String id) {
        this.id = id;
        return this;
    }
}

// [{"n":"cowman","i":"cowman@xxx.com.tw"}, {"n":"cowman1","i":"cowman1@xxx.com.tw"}]

List<Object> ObjectList = new Gson().fromJson(targets, 
new TypeToken<List<Object>>(){}.getType());

This entry was posted in Java. Bookmark the permalink.