Java: Json to Object, Object to Json
Serialize: Person Class to Json
Deserialize: Json to Person
Jar file: gson-2.4.jar
Java file: $j/GsonReadWrite.java
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
class Person {
private int id;
private String name;
private List <Integer> list;
public Person(int id, String name, List <Integer> list){
this.id = id;
this.name = name;
this.list = list;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getList(){
return list;
}
public void setList(List list){
this.list = list;
}
@Override
public String toString() {
String s = "";
for(Integer n : list){
s += n.toString() + " ";
}
return "Person{" + "id=" + id + ", name=" + name + "," + "list=" + s + "}";
}
}
// Object to json
List ls = list(1, 2, 3);
Gson gson = new Gson();
Person person = new Person(10, "Leanna", ls);
String json = gson.toJson(person);
fl("Person to Json");
pl("json=" + json);
// Json to object
Person p = gson.fromJson(json, Person.class);
fl("Json to Person");
pl("Person=" + p.toString());