文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Jackson中json格式的字符串与对象的互相转换方式

2024-04-02 19:55

关注

json格式的字符串与对象的互相转换

Jackson 简介

Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json字符串和xml文档,同样也可以将json、xml转换成Java对象。Jackson所依赖的jar包较少,简单易用并且性能也要相对高些,并且Jackson社区相对比较活跃,更新速度也比较快。

jackson特点

json格式的字符串与对象的转换

使用Jackson必须要在项目导入对应的jar包。

Book.java文件

package cn.hestyle.bean;
public class Book {
	private String id;
	private String name;
	private double price;
	private int pnum;
	private String category;
	private String description;
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, double price, int pnum, String category, String description) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.pnum = pnum;
		this.category = category;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getPnum() {
		return pnum;
	}
	public void setPnum(int pnum) {
		this.pnum = pnum;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + ", pnum=" + pnum + ", category=" + category
				+ ", description=" + description + "]";
	}
}
package cn.hestyle.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
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
@AllArgsConstructor
public class Company {
    private String companyName;
    private List<WebSite> webSites;
}

2.WebSite,站点

@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebSite {
    private String webSiteName;
    private List<User> users;
}

3.User,用户

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String userId;
    private String username;
    private String password;
}

json字符串和对象互转

对象转json字符串

不管你是什么结构的对象,想转json,直接objectMapper.writeValueAsString()搞定。

    
    @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数组字符串


    
    @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数组字符串转数组对象

先演示一下错误的写法先演示一下错误的写法先演示一下错误的写法,重要的事情说三遍!

    
    @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方式取值是错的!

正确做法:

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯