springboot2关于json数据的转化处理,基于object_mapper 1,当今的互联⽹开发⾏业,JSON 这种数据格式越来越成为⽹络开发的主流,尤其是前后端分离之后,⼏乎百分百的数据交互⽅式都是采⽤ JSON
2,由于 SpringMVC 框架的封装性,我们⽇常开发中只需要在控制器加上 @ResponseBody 注解,那么该类中⽅法返回的值就会⾃动转化为 JSON 格式响应给请求⽅,这让我们省去可很多⿇烦
3,但是如果我们在程序中需要⾃⼰转化应该怎么操作呢,SpringBoot 内置了⼀个 ObjectMapper 的类,我们可以直接注⼊使⽤
4,使⽤⽅式如下,⾸先声明⼀个实体类 User,使⽤ lombok 库
package del;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class User {
private Integer id;
private String name;
private Integer sex;
}
5,常⽤的两种转化⽅式
package llection;
import com.ype.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import del.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.st.context.SpringBootTest;
import st.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.LinkedHashMap;
springboot其实就是springimport java.util.LinkedList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CollectionApplicationTests {
/**
* 注⼊ JSON 的操作类
*/
@Autowired
ObjectMapper jsonMapper;
private String jsonStr;
/**
* 将数据转化为 JSON 字符串,这个很简单
*/
@Before
public void before() throws IOException {
List<User> userList = new LinkedList<User>();
for (int i = 1; i <= 20; i++) {
User user = new User();
user.setId(1);
user.setName("张" + i);
user.setSex(i % 2);
userList.add(user);
}
jsonStr = jsonMapper.writeValueAsString(userList);
// System.out.println(jsonStr);
}
/**
* 将 JSON 字符串映射成对应的类集合
* 注意:转化为类时,⽅法的第⼆个参数直接写类.calss 即可
*      但是如果是转化为 List 集合,⽅法的第⼆个参数需要⽤ TypeReference 类
*/
@Test
public void contextLoads() throws IOException{
List<User> userList1 = adValue(jsonStr, new TypeReference<List<User>>() {});
System.out.(0).getClass());  // User
System.out.(0).getId());      // 1
// System.out.println(userList1);
}
/**
* 当然,如果我们只知道 JSON 字符串要转化为 List 集合,但是并不知道 List 内元素的具体类型    * 或者返回的类型是参吃不齐的数据,这时⽅法的第⼆个参数我可以直接写 List.class
* 这样返回的就是⼀个 LinkedHashMap 集合数据,这种⽅式更加灵活
*/
@After
public void after() throws IOException {
List<LinkedHashMap> userList2 = adValue(jsonStr, List.class);
System.out.(0).getClass());  // LinkedHashMap
System.out.(0).get("id"));    // 1
// System.out.println(userList2);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。