Try this code:
public class ContactObject {
private String emailFrom;
private String emailTo;
private String dateChanged;
public ContactObject(String emailFrom, String emailTo, String dateChanged) {
this.emailFrom = emailFrom;
this.emailTo = emailTo;
this.dateChanged = dateChanged;
}
@Override
public String toString() {
return "{email_from:" + emailFrom + ", email_to:" + emailTo + ", DATE_CHANGED:" + dateChanged;
}
}
public class ContactJSON {
private List<ContactObject> data;
public ContactJSON(List<ContactObject> contactList) {
this.data = contactList;
}
}
然后在您的main()
方法中,您可以使用这些类:
public static void main(String[] args) {
List<ContactObject> contactList = new ArrayList<ContactObject>();
ContactObject obj1 = new ContactObject("samwilliams@gmail.com", "mike_haley@gmail.com", "1447666867");
ContactObject obj2 = new ContactObject("smithpaul@gmail.com", "angierussell@gmail.com", "1447668867");
contactList.add(obj1);
contactList.add(obj2);
Gson gson = new Gson();
String json = gson.toJson(new ContactJSON(contactList));
System.out.println(json);
}
输出:
{"data":[{"emailFrom":"samwilliams@gmail.com","emailTo":"mike_haley@gmail.com","dateChanged":"1447666867"},{"emailFrom":"smithpaul@gmail.com","emailTo":"angierussell@gmail.com","dateChanged":"1447668867"}]}