java 用jackSon转JSON 对javabean 进行解析和序列化

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongda.detection.web.model.Person;

public class Test {
	public static void main(String[] args) throws IOException {
		Person person = new Person();
		person.setPersonId(9527);
		person.setPersonName("吴海鑫");
		person.setPersonSex("女");
		person.setLove(new String[] { "LOL", "CF" });

		Person person5 = new Person();
		person5.setPersonId(9527);
		person5.setPersonName("吴海鑫");
		person5.setPersonSex("女");
		person5.setLove(new String[] { "LOL", "CF" });

		// Person类转JSON格式的字符串
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(person);
		System.out.println(json);

		// List<Person>集合转JSON格式字符串
		List<Person> personList = new ArrayList<Person>();
		personList.add(person);
		personList.add(person5);
		ObjectMapper jsonList = new ObjectMapper();
		String jsonString = jsonList.writeValueAsString(personList);
		System.out.println(jsonString);

		String jsonList1 = "[{\"personId\":9527,\"personName\":\"吴海鑫\",\"personSex\":\"女\",\"love\":[\"LOL\",\"CF\"]}"
				+ ",{\"personId\":95275,\"personName\":\"张三\",\"personSex\":\"男\",\"love\":[\"LOL\",\"CF\",\"王者农药\"]}]";

		String json2 = "{\"personId\":9527,\"personName\":\"吴海鑫\",\"personSex\":\"女\",\"love\":[\"LOL\",\"CF\"]}";

		// JSON集合格式字符串转List<Peroson>对象
		ObjectMapper jsontoperson = new ObjectMapper();
		List<Person> person2 = jsontoperson.readValue(jsonList1,
				new TypeReference<List<Person>>() {
				});
		for (Person person3 : person2) {
			System.out.print(person3 + "-----");
		}

		// JSON格式字符串转Person对象
		ObjectMapper jsontoperosn2 = new ObjectMapper();
		Person readValue = jsontoperosn2.readValue(json2, Person.class);
		System.out.println();
		System.out.println(readValue);
	}
}

PS:随便测试用来玩,代码有点不规范,控制台打印结果如下

{"personId":9527,"personName":"吴海鑫","personSex":"女","love":["LOL","CF"]}
[{"personId":9527,"personName":"吴海鑫","personSex":"女","love":["LOL","CF"]},{"personId":9527,"personName":"吴海鑫","personSex":"女","love":["LOL","CF"]}]
person:[personId:9527  personName:吴海鑫  personSex:女  love:[0:LOL  1:CF  ]]-----person:[personId:95275  personName:张三  personSex:男  love:[0:LOL  1:CF  2:王者农药  ]]-----
person:[personId:9527  personName:吴海鑫  personSex:女  love:[0:LOL  1:CF  ]]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值