Guest User

Untitled

a guest
Mar 18th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. public class AssetSerializer extends TypeAdapter<List<Asset>> {
  2.  
  3. @Override
  4. public void write(JsonWriter out, List<Asset> value) throws IOException {
  5. out.beginArray();
  6. for (Asset asset : value) {
  7. out.beginObject();
  8. out.name("name").value(asset.getName());
  9. out.name("code").value(asset.getCode());
  10. out.endObject();
  11. }
  12. out.endArray();
  13. }
  14.  
  15. @Override
  16. public List<Asset> read(JsonReader in) throws IOException {
  17.  
  18. String temp_name = "";
  19. String temp_code = "";
  20. List<Asset> list = new LinkedList<>();
  21. in.beginArray();
  22. while (in.hasNext()) {
  23. switch (in.peek()) {
  24. case BEGIN_OBJECT:
  25. in.beginObject();
  26. while (in.hasNext()) {
  27. switch (in.nextName()) {
  28. case "name":
  29. temp_name = in.nextString();
  30. continue;
  31. case "code":
  32. temp_code = in.nextString();
  33. continue;
  34. }
  35. }
  36. in.endObject();
  37. Asset temp_asset = new Asset(temp_name, temp_code);
  38. list.add(temp_asset);
  39. continue;
  40. }
  41. }
  42. in.endArray();
  43. return list;
  44. }
  45.  
  46. Asset asset1 = new Asset("Asset1", "code_1");
  47. Asset asset2 = new Asset("Asset2", "code_2");
  48. LinkedList<Asset> temp_list = new LinkedList<Asset>();
  49. temp_list.add(asset1);
  50. temp_list.add(asset2);
  51. Type assetsType = new TypeToken<List<Asset>>(){}.getType();
  52.  
  53. Gson gson = new GsonBuilder()
  54. .setPrettyPrinting()
  55. .registerTypeAdapter(assetsType, new AssetSerializer())
  56. .create();
  57. String json = gson.toJson(temp_list);
Add Comment
Please, Sign In to add comment