欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSON与对象的相互转换

程序员文章站 2024-03-16 08:52:34
...

JSON与对象的相互转换

一、fastjson

		//1、maven依赖
		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

			//2、实体类

			import lombok.*;
			@Getter
			@Setter
			@NoArgsConstructor
			@AllArgsConstructor
			@ToString
			public class User {
				private String name;
				private Integer age;
			}

		//3.测试

		User xx = new User("xx", 12);
        User ll = new User("ll", 12);
        User jj = new User("jj", 12);
        List<User> users = Arrays.asList(xx, ll, jj);
      
        //对象转JSON字符串
        String jsonString = JSON.toJSONString(users);
        System.out.println(jsonString); //[{"age":12,"name":"xx"},{"age":12,"name":"ll"},{"age":12,"name":"jj"}]

        //json字符串
        //对象类型
        System.out.println(JSON.parseArray(jsonString, User.class)); 
        //[User(name=xx, age=12), User(name=ll, age=12),User(name=jj, age=12)]
       
        System.out.println(JSON.parseObject(jsonString,List.class));
        //[{"name":"xx","age":12}, {"name":"ll","age":12}, {"name":"jj","age":12}]

二、jackson

		//1、maven依赖
		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.4</version>
        </dependency>
		//2、测试
		 private final ObjectMapper objectMapper = new ObjectMapper();
	    @Test
	    public void test() throws JsonProcessingException {
	        User xx = new User("xx", 12);
	        User ll = new User("ll", 12);
	        User jj = new User("jj", 12);
	        List<User> users = Arrays.asList(xx, ll, jj);
	
	        //将对象转换为JSON
	        System.out.println(objectMapper.writeValueAsString(users));
	        //[{"name":"xx","age":12},{"name":"ll","age":12},{"name":"jj","age":12}]
	
	        //将JSON转换成对象
	        List<User> user = objectMapper.readValue(objectMapper.writeValueAsString(users), List.class);
	        System.out.println(user);
	        //[{name=xx, age=12}, {name=ll, age=12}, {name=jj, age=12}]
	
	    }
相关标签: 笔记 json java