Ralf Wickum
Ralf Wickum

Reputation: 3284

Create on Android a GSON from any Container like List

I have a java.util.List<Student>; whereas Student is a simple class with few attributes like String name, String forName, int id, double averageCredtis;

As in this code:

class Student {
  private String foreName;
  private String surName;
  private int id;
  private double averageCredits;

  public Student(String f, String n, int id, double aCred)
  {
    this.foreName = f;
    this.surName = n;
    this.id = id;
    this. averageCredits = aCred;
  }
}

Then I create multiple objects during runtime:

Student a = new Student("Alice", "Aaa", 123, 1.6);
Student b = new Student("Bob", "Bbb", 223, 1.0);
Student c = new Student("Chris", "Ccc", 457, 3.6);

I used to store them in a Lisdt by means of myList.add(a);.

I would like to generate a GSON String like:

{ "GlobalVal": "Value", "GlobalNumber": "234", "Student": {"Surname": "Aaa","Forename": "Alice", "id": 123, >"averageCredit": 1.7 } "Student": {"Surname": "Bbb","Forename": "Bob", "id": >223,"averageCredit": 1.0 } }

Upvotes: 1

Views: 45

Answers (2)

Adi
Adi

Reputation: 425

Use Gson lib to achieve the same.

Below link answers you question precisely. Refer : http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Upvotes: 1

Gowtham Raj
Gowtham Raj

Reputation: 2955

Create a class named Container

class Container{
    String globalVal;
    int globalInt;
    List<Student> students;
}

Use GSON library to convert this to JSON. Create an instance of the above class and store the values.

Container obj = new Container();
Gson gson = new Gson();

// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

Upvotes: 1

Related Questions