Java单个对象和List对象转换成JSON格式

目录

 

(一)使用单个对象转换JSON对象

(二)多个对象存到List,再转换成JSON


(一)使用单个对象转换JSON对象

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

import com.css.eshop.exception.DataAccessException;
import com.css.eshop.model.VoucherInfo;
import com.css.eshop.util.HttpClientUtil;
import com.css.eshop.util.LoadStaticReferenceTables;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TestPut {
	protected Log logger = LogFactory.getLog(this.getClass().getName());
	
	@Test
	public void getOneJson(){//测试转换成Json,单个对象
		VoucherInfo vo1=new VoucherInfo();
		vo1.setVoucherValue(2131);vo1.setVoucherCode("小可爱的");
		JSONObject updateJsonObj = JSONObject.fromObject(vo1);//转换成json格式
		logger.info("---转换成json格式:---"+updateJsonObj.toString());//提取access_token节点数据
	}
}

输出转换后日志:

Java单个对象和List对象转换成JSON格式

17-10-2018 17:35 INFO  TestPut:35 - ---转换成json格式:---{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的","voucherType":"","voucherValue":2131,"weight":0,"weightUnit":""}
 

(二)多个对象存到List,再转换成JSON

	@Test
	public void getArrayList(){//测试转换成Json,List转换成JSONList
		List<VoucherInfo> vouchersList=new ArrayList<VoucherInfo>();
		VoucherInfo vo1=new VoucherInfo();
		VoucherInfo vo2=new VoucherInfo();
		vo1.setVoucherValue(2131);vo1.setVoucherCode("小可爱的");
		vo2.setVoucherValue(100);vo2.setVoucherCode("小可爱的222");
		vouchersList.add(vo1);vouchersList.add(vo2);
		JSONArray jsonArray = JSONArray.fromObject(vouchersList);
		logger.info("--获取到转换为json格式的内容:"+jsonArray.toString());//提取access_token节点数据
		
	}

输出日志:

Java单个对象和List对象转换成JSON格式

17-10-2018 17:36 INFO  TestPut:47 - --获取到转换为json格式的内容:[{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的","voucherType":"","voucherValue":2131,"weight":0,"weightUnit":""},{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的222","voucherType":"","voucherValue":100,"weight":0,"weightUnit":""}]