zoukankan      html  css  js  c++  java
  • gson在java和json串之间的应用

    public class JsonToJavaUtil {
    /**
    * 将json转成成javaBean对象
    *
    * @param <T>
    * 返回类型
    * @param json
    * 字符串
    * @param clazz
    * 需要转换成的类
    * @return
    */

    public static <T> List<T> jsonToJavaBean(String json, Type type) {
      List<T> list = new ArrayList<T>();
      try {
          Gson gson = new Gson();
          list = gson.fromJson(json, type);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return list;
      }

    }

    -------------------

    测试代码:

    String str = "[{code:'0',name:'we',hsCode:'rwer',jtCode:'1',invoiceno:'r12',weight:12,capacity:45},{code:'0',name:'fgh',hsCode:'fgh',jtCode:'1',invoiceno:'dfg',weight:45,capacity:45}]";
    Gson gson = new Gson();

    List<TBLGoods> list = JsonToJavaUtil.jsonToJavaBean(str, new TypeToken<List<TBLGoods>>() {}.getType());

    for (int i = 0; i < list.size(); i++) {
    System.out.println("==================="+list.get(i).getName());
    }

    测试结果:

    ===================we
    ===================fgh

  • 相关阅读:
    树的重心备忘
    Hdu 2196
    HDU 1520
    TOJ1068 商务旅行
    携程HDU第一场1001
    USACO 4.3.2 The Primes
    Html常用标签的应用
    Html
    开班心得
    for循环练习及字符串处理
  • 原文地址:https://www.cnblogs.com/lbangel/p/3147727.html
Copyright © 2011-2022 走看看