1

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.

Gaurav Deshpande
  • 444
  • 1
  • 7
  • 25

1 Answers1

3

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)

Community
  • 1
  • 1
Pratik
  • 944
  • 4
  • 20