文章目录
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);