Gson - putting and getting ArrayList of composite objects

十年热恋 提交于 2019-12-11 11:32:26

问题


I have class NameAndPostion in which I am going to store name and position of users. And I have created ArrayList of objects of NameAndPosition.

ArrayList<NameAndPosition> LocSenders = new ArrayList<NameAndPosition>();

Now I have converted LocSenders into JSON string by using Gson library

Gson gson = new Gson();
String json = gson.toJson(LocSenders);

I did this conversion to save LocSenders in Shared Pref.
Now I want to retrieve all objects in 'LocSenders' which I have stored using Gson JSON conversion.

I want to do this work using Gson library.
I am not getting the Gsons method gson.fromJson(json, classOfT). So how to do that properly?

NameAndPostion.java

public class NameAndPosition {

    private String name = "";
    private LatLng position = null;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public LatLng getPosition() {
        return position;
    }
    public void setPosition(LatLng position) {
        this.position = position;
    }

}

Thanks in advance.


回答1:


Here is example of convert to JSON and from JSON using gson.

//Convert to JSON
System.out.println(gson.toJson(employee));

//Convert to java objects
System.out.println(gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER'],'birthDate':'17/06/2014'}"
                            , Employee.class));

Deserialize collection

List<Employee> yourClassList = new Gson().fromJson(jsonArray, Employee.class);

For generic Collection.

Type listType = new TypeToken<ArrayList<YourClass>>() {
                    }.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);

you can also refere below link.

Google Gson - deserialize list<class> object? (generic type)



来源:https://stackoverflow.com/questions/29426062/gson-putting-and-getting-arraylist-of-composite-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!