使用JackSon

2014年12月23日21:54:56 心情稍微好转

1、导入 jar 包 

jackson-annotations-2.4.4.jar 下载地址

jackson-core-2.4.4.jar 下载地址

jackson-databind-2.4.4.jar 下载地址

2、使用的具体步骤

(1)、创建com.fasterxml.jackson.databind.ObjectMapper对象

(2)、调用ObjectMapper 的 wirteValueAsString 方法把java对象或集合转为JSON字符串

ObjectMapper objectMapper = new ObjectMapper();

String jsonstr = objectMapper.writeValueAsString(customer);

(3)注意:

①、JackSon根据getter来定位Json 对象的属性,而不是字段!

②、可以在类的getter 方法上添加注解:com.fasterxml.jackson.annotation.JsonIgnore 在转为 JSON对象时以忽略改属性


Customer.java

package com.gditc.beans;

import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Customer {

	private String name;
	private String id;

	public Customer(String name, String id) {
		super();
		this.name = name;
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCity() {
		return "Guangzhou";
	}

	@JsonIgnore
	public String getBirthday() {
		return "1990-07-26";
	}

	public static void main(String[] args) throws JsonProcessingException {
		// 1.导入 jar包
		// 2.创建ObjectMapper对象
		ObjectMapper objectMapper = new ObjectMapper();

		// 3.调用mapper的writeValueAsString() 方法把一个对象转为一个JSON字符串
		Customer customer = new Customer("AAAA", "1001");
		String jsonstr = objectMapper.writeValueAsString(customer);
		System.out.println(jsonstr);

		// 4注意:JSON使用getter方法把一个对象转为一个JSON字符串
		// 5.可以通过添加注解 com.fasterxml.jackson.annotation.JsonIgnore
		// 忽略某个getter定义的属性
		List<Customer> customers = Arrays.asList(customer, new Customer("BBB", "1002"));
		jsonstr = objectMapper.writeValueAsString(customers);
		System.out.println(jsonstr);

	}

}
觉得挺可以的,分享给大家


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值