码迷,mamicode.com
首页 > 编程语言 > 详细

java如何把对象转化成json

时间:2020-10-12 20:48:41      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:file   map   date   core   throw   imp   user   cep   rac   

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

}

@Test
public void test2() throws IOException {
//1、创建对象
User user = new User("zmy",20,"male");
user.setBirthday(new Date());
//2、创建jackson的核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);

}

@Test
public void test3() throws IOException {
//1、创建user和list对象
User user = new User("zmy",20,"male",new Date());
User user1 = new User("light",10,"male",new Date());
User user2 = new User("cityboy",5,"male",new Date());

List<User> ps = new ArrayList<User>();
ps.add(user);
ps.add(user1);
ps.add(user2);
//2、创建jackson的核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(ps);
System.out.println(json);

}

@Test
public void test4() throws IOException {
Map<String,Object> map = new HashMap<String, Object>();
map.put("name","zmy");
map.put("age",15);
map.put("gender","男");

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
System.out.println(json);
}

//演示 json字符串转换为java对象
@Test
public void test5() throws IOException {
//初始化json字符串
String json="{\"gender\":\"男\",\"name\":\"zmy\",\"age\":15}";
//创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//转换json字符串为java对象
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}

java如何把对象转化成json

标签:file   map   date   core   throw   imp   user   cep   rac   

原文地址:https://www.cnblogs.com/YuyuanNo1/p/13804445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!