jackson用法string转json,jackson 对象转字符串
目录
json格式的字符串与对象的互相转换杰克逊简介杰克逊特点数据格式的字符串与对象的转换杰克逊进行数据转对象,对象转数据总结JavaBean准备数据字符串和对象互转数据数组字符串和数组(集合)对象互转
json格式的字符串与对象的互相转换
Jackson 简介
杰克逊是一个简单基于爪哇应用库,杰克逊可以轻松的将爪哇对象转换成数据字符串和可扩展标记语言文档,同样也可以将json、xml转换成爪哇对象杰克逊。所依赖的冲突包较少,简单易用并且性能也要相对高些,并且杰克逊社区相对比较活跃,更新速度也比较快。
jackson特点
容易使用-杰克逊应用程序接口提供了一个高层次外观,以简化常用的用例。无需创建映射- API提供了默认的映射大部分对象序列化。性能高-快速,低内存占用,适合大型对象图表或系统。干净的约翰逊-杰克逊公司创建一个干净和紧凑的数据结果,这是让人很容易阅读。不依赖-库不需要任何其他的库,除了JDK。开源代码杰克逊是开源的,可以免费使用。
json格式的字符串与对象的转换
使用杰克逊必须要在项目导入对应的冲突包。
Book.java文件
包cn。何风格。豆;公共类书{私有字符串id;私有字符串名称;私人双倍价格;私有int pnum私有字符串类别;私有字符串描述;公书(){ super();//TODO自动生成的构造函数stub}public Book(字符串id,字符串名称,double price,int pnum,字符串类别,字符串描述){ super();this . id=id this . name=name this . price=价格;this . pnum=pnum this . category=category this . description=描述;}公共字符串getId(){返回id;} public void setId(String id){ this。id=id} public String getName(){ return name;} public void set name(String name){ this。name=名称;} public double getPrice(){ return price;}公共void设置价格(双倍价格){ this。价格=价格;} public int getPnum(){ return pnum;} public void set pnum(int pnum){ this。pnum=pnum}公共字符串get category(){返回类别;}public void setCategory(字符串类别){ this.category=category}公共字符串get description(){返回描述;}public void setDescription(字符串描述){ this . description=description } @ override public String to String(){ return Book[id= id ,name= name ,price= price ,pnum= pnum ,category= category ,description= description ];} }包cn。何风格。utils导入Java。io。io异常;导入Java。util。ArrayList导入Java。util。列表;导入组织。代号豪斯。杰克逊。jsongenerationexception导入org。代号豪斯。杰克逊。地图。jsonmappingexcepti
on;import org.codehaus.jackson.map.ObjectMapper;import cn.hestyle.bean.Book;public class JacksonDemo01 {public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {ObjectMapper objectMapper = new ObjectMapper();//将对象转换为json格式的字符串Book book = new Book("1001", "Java入门到入土", 99.9, 100, "编程开发", "你懂得!");String bookJsonStr = objectMapper.writeValueAsString(book);System.out.println(bookJsonStr);//将集合、数组对象转换为json格式的字符串List<Book> bookList = new ArrayList<Book>();bookList.add(new Book("1001", "Java入门到入土", 99.9, 100, "编程开发", "你懂得!"));bookList.add(new Book("1002", "Python入门到入土", 89.9, 100, "编程开发", "你懂得!"));bookList.add(new Book("1003", "C++入门到入土", 89.9, 200, "编程开发", "你懂得!"));String bookListJsonStr = objectMapper.writeValueAsString(bookList);System.out.println(bookListJsonStr);//将json格式的字符串转化为对象//字符串中含有双引号,需要使用反斜杠转义String bookString = "{"id":"1001","name":"Java入门到入土","price":99.9,"pnum":100}";//Book必须有无参的构造方法Book book2 = objectMapper.readValue(bookString, Book.class);System.out.println(book2);}}控制台输出:
Jackson进行json转对象,对象转json总结
在前后端分离的项目中,后端经常涉及到json与对象互转的场景。阿里巴巴的Fastjson是好用,但是,因为技术领导的原因(可能因为fastjson1的各种问题很多吧),不让用,所以就需要选择其他技术栈。当前比较常用的是SpringBoot自带的Jackson或者谷歌的Gson。
下面,做一下使用Jackson的总结。
JavaBean准备
1.Company,公司
@Data@NoArgsConstructor@AllArgsConstructorpublic class Company { private String companyName; private List<WebSite> webSites;}
2.WebSite,站点
@Data@NoArgsConstructor@AllArgsConstructorpublic class WebSite { private String webSiteName; private List<User> users;}
3.User,用户
@Data@NoArgsConstructor@AllArgsConstructorpublic class User { private String userId; private String username; private String password;}
json字符串和对象互转
对象转json字符串
不管你是什么结构的对象,想转json,直接objectMapper.writeValueAsString()搞定。
/** * 序列化:对象转json字符串,包含多个数组 * */ @Test public void testObject2Json2() { User user2 = new User("1","上海辟谣专属队","职业辟谣,不信谣,不传谣,呵呵"); List<User> users = new ArrayList<>(); users.add(user2); WebSite webSite = new WebSite(); webSite.setWebSiteName("xxxxxx.com"); webSite.setUsers(users); List<WebSite> webSites = new ArrayList<>(); webSites.add(webSite); Company company = new Company(); company.setCompanyName("yyyyyy"); company.setWebSites(webSites); ObjectMapper objectMapper = new ObjectMapper(); try { String jsonString = objectMapper.writeValueAsString(company); System.out.println(jsonString); } catch (JsonProcessingException e) { log.error("error: ", e); } }
输出:
{"companyName":"yyyyyy","webSites":[{"webSiteName":"xxxxxx.com","users":[{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}]}]}
json字符串转对象
注意:这种情形是json对象字符串,不能是json数组字符串,后面会说到。
@Test public void testJson2Object() { String json = "{"companyName":"yyyyyy","webSites":[" + "{"webSiteName":"xxxxxx.com","users":[{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}]}" + "]}"; ObjectMapper objectMapper = new ObjectMapper(); try { Company company = objectMapper.readValue(json, Company.class); System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername()); } catch (JsonProcessingException e) { log.error("error: ", e); } }
输出:
上海辟谣专属队
json数组字符串和数组(集合)对象互转
有个大坑
数组对象转json数组字符串
/** * 序列化:数组对象转json数组类型的字符串 * */ @Test public void testObjectArray2JsonArrayString() { User user1 = new User("1","上海带刀沪卫","带刀大佬"); User user2 = new User("1","上海辟谣专属队","职业辟谣,不信谣,不传谣,呵呵"); List<User> users = new ArrayList<>(); users.add(user1); users.add(user2); ObjectMapper objectMapper = new ObjectMapper(); try { String json = objectMapper.writeValueAsString(users); System.out.println(json); } catch (JsonProcessingException e) { log.error("error: ", e); } }
输出:
[{"userId":"1","username":"上海带刀沪卫","password":"带刀大佬"},{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}]
json数组字符串转数组对象
先演示一下错误的写法,先演示一下错误的写法,先演示一下错误的写法,重要的事情说三遍!
/** * 反序列化:数组类型的json字符串转对象数组 * */ @Test public void testJsonArrayString2ObjectArray() { String json = "[" + "{"userId":"1","username":"上海带刀沪卫","password":"带刀大佬"}" + ",{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}" + "]"; ObjectMapper objectMapper = new ObjectMapper(); try {//错误写法 List<User> list = objectMapper.readValue(json, List.class); list.forEach(user -> { System.out.println(user.getUsername()); }); } catch (JsonProcessingException e) { log.error("error: ", e); } }
输出异常:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xywei.springboot.springtestdemo.entity.User
at java.util.ArrayList.forEach(ArrayList.java:1259) at com.xywei.springboot.springtestdemo.junit.TestUseJackson.testJsonArrayString2ObjectArray(TestUseJackson.java:160) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at
#省略大段……Process finished with exit code -1
因为实际转成了map类型,所以使用List方式取值是错的!
正确做法:
/** * 反序列化:数组类型的json字符串转对象数组 * */ @Test public void testJsonArrayString2ObjectArray() { String json = "[" + "{"userId":"1","username":"上海带刀沪卫","password":"带刀大佬"}" + ",{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}" + "]"; ObjectMapper objectMapper = new ObjectMapper(); try { TypeReference<List<User>> typeReference = new TypeReference<List<User>>() { }; List<User> list = objectMapper.readValue(json, typeReference); list.forEach(user -> { System.out.println(user.getUsername()); }); } catch (JsonProcessingException e) { log.error("error: ", e); } }
最终输出:
上海带刀沪卫
上海辟谣专属队
同时,对多层嵌套的数组也适用:
@Test public void testJsonArrayString2ObjectArray2() { String json = "[" + "{" + ""companyName":"yyyyyy","webSites":[" + "{"webSiteName":"xxxxxx.com","users":[" + "{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}" + "]" + "}" + "]" + "}" + "]"; ObjectMapper objectMapper = new ObjectMapper(); try { TypeReference<List<Company>> typeReference = new TypeReference<List<Company>>() { }; List<Company> list = objectMapper.readValue(json, typeReference); list.forEach(company -> { System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername()); }); } catch (JsonProcessingException e) { log.error("error: ", e); } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。