1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Json字符串和对象相互转换

Json字符串和对象相互转换

时间:2022-01-16 07:49:12

相关推荐

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);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。