java把对象转换成json_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);

}

@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 ps = new ArrayList();

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 map = new HashMap();

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值