软件编程
位置:首页>> 软件编程>> java编程>> Json字符串转Java对象和List代码实例

Json字符串转Java对象和List代码实例

作者:听风的dog  发布时间:2022-03-11 15:47:09 

标签:Json,字符串,转,Java,List

对象POJO和JSON互转


public class JsonUtil {
 /**
  * JSON 转 POJO
  */
  public static <T> T getObject(String pojo, Class<T> tclass) {
     try {
       return JSONObject.parseObject(pojo, tclass);
     } catch (Exception e) {
       log.error(tclass + "转 JSON 失败");
     }
     return null;
  }

/**
  * POJO 转 JSON  
  */
  public static <T> String getJson(T tResponse){
    String pojo = JSONObject.toJSONString(tResponse);
    return pojo;
  }

}

List集合和JSON互转工具类


public class JsonListUtil {
 /**
  * List<T> 转 json 保存到数据库
  */
 public static <T> String listToJson(List<T> ts) {
   String jsons = JSON.toJSONString(ts);
   return jsons;
 }

/**
  * json 转 List<T>
  */
 public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
   @SuppressWarnings("unchecked")
   List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
   return ts;
 }

}

来源:https://www.cnblogs.com/winddogg/p/10924487.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com