Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.google.gson.Gson;
- import com.google.gson.JsonArray;
- import com.google.gson.JsonParser;
- import java.util.ArrayList;
- public class Serialization
- {
- public static void main(String [] args)
- {
- ArrayList<Element> studentsList = new ArrayList<>();
- studentsList.add(new Element("Pedro",10,"pedro@gmail.com",
- new Phone("91000111","mobile")));
- studentsList.add(new Element("Joao",11,"joao@gmail.com",
- new Phone("546784987","mobile")));
- studentsList.add(new Element("RoseGay",12,"rose@gmail.com",
- new Phone("7879846","mobile")));
- Element director = new Element("Alberto", 1, "alberto@gmail.com",
- new Phone("91213123", "mobile"));
- Classe newClass = new Classe("TurmaA", director,studentsList);
- // Serialize java object to JSON
- Gson gson = new Gson();
- String json = gson.toJson(newClass);
- System.out.println("Serialized java object: \n" + json);
- // Deserialization
- JsonParser parser = new JsonParser();
- JsonArray arry = new JsonArray();
- arry = parser.parse(json).getAsJsonArray();
- // Retirar e identificar o objecto
- String classname = gson.fromJson(arry.get(0), String.class);
- Element director_d = gson.fromJson(arry.get(1), Element.class);
- Element studentList_d = gson.fromJson(arry.get(2), Element.class);
- System.out.printf("Deserialized \n" +
- "Class name: %s\n" +
- "Director element: %s\n" +
- "Student class: %s\n",
- classname, director_d.toString(), studentList_d.toString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement