Advertisement
Guest User

Untitled

a guest
Sep 17th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import com.google.gson.Gson;
  2. import com.google.gson.JsonArray;
  3. import com.google.gson.JsonParser;
  4.  
  5. import java.util.ArrayList;
  6.  
  7. public class Serialization
  8. {
  9.  
  10. public static void main(String [] args)
  11. {
  12.  
  13. ArrayList<Element> studentsList = new ArrayList<>();
  14.  
  15. studentsList.add(new Element("Pedro",10,"pedro@gmail.com",
  16. new Phone("91000111","mobile")));
  17. studentsList.add(new Element("Joao",11,"joao@gmail.com",
  18. new Phone("546784987","mobile")));
  19. studentsList.add(new Element("RoseGay",12,"rose@gmail.com",
  20. new Phone("7879846","mobile")));
  21.  
  22. Element director = new Element("Alberto", 1, "alberto@gmail.com",
  23. new Phone("91213123", "mobile"));
  24.  
  25.  
  26.  
  27. Classe newClass = new Classe("TurmaA", director,studentsList);
  28.  
  29. // Serialize java object to JSON
  30.  
  31. Gson gson = new Gson();
  32.  
  33. String json = gson.toJson(newClass);
  34.  
  35. System.out.println("Serialized java object: \n" + json);
  36.  
  37. // Deserialization
  38.  
  39. JsonParser parser = new JsonParser();
  40.  
  41. JsonArray arry = new JsonArray();
  42.  
  43. arry = parser.parse(json).getAsJsonArray();
  44.  
  45. // Retirar e identificar o objecto
  46.  
  47. String classname = gson.fromJson(arry.get(0), String.class);
  48.  
  49. Element director_d = gson.fromJson(arry.get(1), Element.class);
  50.  
  51. Element studentList_d = gson.fromJson(arry.get(2), Element.class);
  52.  
  53. System.out.printf("Deserialized \n" +
  54. "Class name: %s\n" +
  55. "Director element: %s\n" +
  56. "Student class: %s\n",
  57. classname, director_d.toString(), studentList_d.toString());
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66. }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement