浅谈Java对象数据转换为JSON对象数据

4 篇文章 0 订阅

1、Java对象列表转换为JSON对象数组,并转为字符串

JSONArray jsonArray = JSONArray.fromObject(list);
String jsonArrayStr = jsonArray.toString();


2、把Java对象转换成JSON对象,并转化为字符串

JSONObject jsonObject = JSONObject.fromObject(obj);
String jsonObjectStr = jsonObject.toString();


3、过滤不需要转换为JSON格式的属性

使用jsonConfig对象的setExcludes()方法,传入参数为待过滤属性组成的数组。

JsonConfig cfg = new JsonConfig();
cfg.setExcludes(new String[] {“待过滤属性1”, “待过滤属性2”, ..., “待过滤属性n”});


4、实例

package com.ajax.test;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class Customer {
	public Customer(String name, String id) {
		super();
		this.name = name;
		this.id = id;
	}
	private String name;
	private String 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 static void main(String[] args) throws JsonProcessingException {
		//包含多个对象的List集合转换为JSON格式
		List<Customer> list = new ArrayList<Customer>();
		Customer c1 = new Customer("Alice", "001");
		Customer c2 = new Customer("Bruce", "002");
		Customer c3 = new Customer("Cindy", "003");
		list.add(c1);
		list.add(c2);
		list.add(c3);
		JsonConfig config1 = new JsonConfig();
		//过滤List集合中的Customer对象的id属性不生成JSON
		config1.setExcludes(new String[] {"id"});
		JSONArray jsonArray = JSONArray.fromObject(list, config1);
		System.out.println(jsonArray.toString());
		//一个对象转换为JSON格式
		Customer c = new Customer("Boss", "004");
		JsonConfig config2 = new JsonConfig();
		//过滤Customer对象的id属性不生成JSON
		config2.setExcludes(new String[] {"id"});
		JSONObject jsonObject = JSONObject.fromObject(c, config2);
		System.out.println(jsonObject.toString());
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值