Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. public class JsonStringToObect {
  2.  
  3. public <T> T convertJsonValueToObjectByKey(String targetString, String key, Type ObjectType) {
  4. // using JsonParser When Json to JsonObject
  5. JsonObject jsonObject = new JsonParser().parse(targetString).getAsJsonObject();
  6.  
  7. // using Gson When Json to Java Object (Class value)
  8. Gson gson = new Gson();
  9. return gson.fromJson(jsonObject.get(key), ObjectType);
  10. }
  11.  
  12. public void example() {
  13. String testString = "{ \"code\" : \"200\", \"msg\" : \"OK\", \"products\" : [{\"product_id\":\"6216\",\"y\":\"0.6619\",\"point_id\":\"6216\",\"x\":\"0.6094\"},{\"product_id\":\"6217\",\"y\":\"0.6563\",\"point_id\":\"6217\",\"x\":\"0.5000\"}], \"top\": {\"product_id\":\"6216\",\"y\":\"0.6619\",\"point_id\":\"6216\",\"x\":\"0.6094\"} }";
  14.  
  15. // ex. 1
  16. CoordinateModel result1 = convertJsonValueToObjectByKey(testString, "top", CoordinateModel.class);
  17.  
  18. // ex. 2 ) List
  19. List<CoordinateModel> result2 = convertJsonValueToObjectByKey(testString, "products", new TypeToken<ArrayList<CoordinateModel>>(){}.getType());
  20.  
  21. // ex. 3 ) String
  22. JsonObject jsonObject = new JsonParser().parse(testString).getAsJsonObject();
  23. String result3 = jsonObject.get("code").getAsString()
  24. }
  25.  
  26. public class CoordinateModel {
  27. @SerializedName(value = "product_id", alternate = {"id"})
  28. private Integer productsId;
  29. @SerializedName("x")
  30. private String positionX;
  31. @SerializedName("y")
  32. private String positionY;
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement