如何将java对象转换成json数据



package cn.hopetesting.com.test;

import cn.hopetesting.com.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


/**
* @author newcityman
* @date 2019/9/17 - 23:12
步骤1、导入jackson的三个包
2、创建一个user对象,并赋值
3、创建jackson的核心对象ObjectMapper
4、调用ObjectMapper的writevalue等相关方法
*/
public class TestJson {
@Test
public void test1() throws IOException {
//1、创建对象
User user = new User("zmy",20,"male");
//2、创建jackson的核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3、转换
/*try {
String json = mapper.writeValueAsString(user);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}*/
//将数据写到d://a.txt文件中
// mapper.writeValue(new File("d://a.txt"),user);
//将数据关联到writer中
mapper.writeValue(new FileWriter("d://b.txt"),user);

}
}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11538020.html