问题
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