Json字符串和对象相互转换
生活随笔
收集整理的這篇文章主要介紹了
Json字符串和对象相互转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1、JsonUtil
- 工具類
- 把對象轉換為json字符串
- 把json字符串轉換為對象
- 把json字符串轉換為List集合
- 2、Gson
- 把對象轉換為json字符串
- 把json字符串轉換為對象
- 把json字符串轉換為List對象
- 把list轉換為json格式字符串
1、JsonUtil
工具類
import com.fasterxml.jackson.databind.ObjectMapper;public class JsonUtil {private static final ObjectMapper MAPPER = new ObjectMapper();/*** 把對象轉字符串* @param data* @return*/public static String objectToJson(Object data){try {return MAPPER.writeValueAsString(data);}catch (Exception e){e.printStackTrace();}return null;}/*** json字符串轉對象* @param jsonData* @param beanType* @param <T>* @return*/public static <T> T jsonToPojo(String jsonData, Class<T> beanType){try {T t = MAPPER.readValue(jsonData,beanType);return t;}catch (Exception e){e.printStackTrace();}return null;}}Jackson
把對象轉換為json字符串
ObjectMapper objectMapper = new ObjectMapper(); People peo = new People(); String jsonStr = objectMapper.writeValueAsString(peo);把json字符串轉換為對象
ObjectMapper objectMapper = new ObjectMapper(); People peo = objectMapper.readValue(jsonStr, People.class);把json字符串轉換為List集合
ObjectMapper objectMapper = new ObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class); List<People> list = objectMapper.readValue(jsonStr, javaType);2、Gson
把對象轉換為json字符串
Gson gson = new Gson(); String userJson = gson.toJson(userObject);把json字符串轉換為對象
// str代表的是json字符串,Student.class代表的是你要轉成的類型
Gson gson = new Gson();
Student student = gson.fromJson(str, Student.class);
把json字符串轉換為List對象
Type type = new TypeToken<List<User>>() {}.getType(); List<User> userLists = new Gson().fromJson(json, type);把list轉換為json格式字符串
String json = new Gson().toJson(list);總結
以上是生活随笔為你收集整理的Json字符串和对象相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redis(案例四:购物车实现案例-Ha
- 下一篇: MyBatisPlus分页