Gson解析纯Json数组

忘是亡心i 2022-04-02 10:54 344阅读 0赞
  1. [
  2. {
  3. "type": "123",
  4. "value": 123
  5. },
  6. {
  7. "type": "234",
  8. "value": 234
  9. }
  10. ]
  11. import java.lang.reflect.Type;
  12. import java.util.ArrayList;
  13. import java.util.Arrays;
  14. import java.util.List;
  15. import com.google.gson.Gson;
  16. import com.google.gson.JsonObject;
  17. import com.google.gson.reflect.TypeToken;
  18. public class DataFactory
  19. {
  20. public static Object getInstanceByJson(Class<?> clazz, String json)
  21. {
  22. Object obj = null;
  23. Gson gson = new Gson();
  24. obj = gson.fromJson(json, clazz);
  25. return obj;
  26. }
  27. /**
  28. * @author I321533
  29. * @param json
  30. * @param clazz
  31. * @return
  32. */
  33. public static <T> List<T> jsonToList(String json, Class<T[]> clazz)
  34. {
  35. Gson gson = new Gson();
  36. T[] array = gson.fromJson(json, clazz);
  37. return Arrays.asList(array);
  38. }
  39. /**
  40. * @param json
  41. * @param clazz
  42. * @return
  43. */
  44. public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz)
  45. {
  46. Type type = new TypeToken<ArrayList<JsonObject>>()
  47. {}.getType();
  48. ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);
  49. ArrayList<T> arrayList = new ArrayList<>();
  50. for (JsonObject jsonObject : jsonObjects)
  51. {
  52. arrayList.add(new Gson().fromJson(jsonObject, clazz));
  53. }
  54. return arrayList;
  55. }
  56. }

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Gson解析JSON

    Gson解析JSON(包含动态KEY、未知字段处理方法) 有时在解析json数据中的字段key是动态可变的时候,由于Gson是使用静态注解的方式来设置实体对象的,因此我们很难

    相关 gson解析json

    为什么使用Gson > Gson是google一个比较流行的开源项目,相比于json,Gson的功能更加全面,性能更加强大,使用方式也更加便捷简单。 一般使用Gson生

    相关 使用Gson解析json

    Java对象和Json之间的互转,一般用的比较多的两个类库是Jackson和Gson,下面记录一下Gson的学习使用。 基础概念:  Serialization:序列化,使