Java 处理json常用代码

本文介绍了一种使用 net.sf.json 库在 Java 中进行 JSON 数据转换的方法,包括数组、集合、对象及实体类到 JSON 的转换,同时也展示了如何将 JSON 字符串反序列化为 Java 对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本工程代码已上传至资源,如有需要,请自行下载。
package com.michael;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;

public class JsonLibTest {
	/**
	 * 将数组转换为json对象
	 */
	// @Test
	public void testArrayToJSON() {
		boolean[] boolArray = new boolean[] { true, false, true };
		JSONArray jsonArray = JSONArray.fromObject(boolArray);
		System.out.println("testArrayToJSON----jsonArray-----" + jsonArray);
	}

	/**
	 * 将集合转换为json
	 */
	// @Test
	public void testListToJSON() {
		List<String> list = new ArrayList<String>();
		list.add("first");
		list.add("second");
		JSONArray jsonArray = JSONArray.fromObject(list);
		System.out.println("testListToJSON---jsonArray----" + jsonArray);
	}

	/**
	 * 将json字符串转换为json对象
	 */
	@Test
	public void testJsonStrToJSON() {
		JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");
		System.out.println("testJsonStrToJSON---jsonArray----" + jsonArray);
	}

	/**
	 * 将map转换为json对象
	 */
	@Test
	public void testMapToJSON() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "json");
		map.put("bool", Boolean.TRUE);
		map.put("int", new Integer(1));
		map.put("arr", new String[] { "a", "b" });
		map.put("func", "function(i){ return this.arr[i]; }");
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println("testJsonStrToJSON---jsonObject----" + jsonObject);
	}

	// 将实体类转换为json
	@Test
	public void testBeadToJSON() {
		Car bean = new Car();
		bean.setId("001");
		bean.setName("hello");
		bean.setDate(new Date());

		List<Car> cars = new ArrayList<Car>();
		cars.add(new Car("AUDI"));
		cars.add(new Car("BMW"));
		cars.add(new Car("QQ"));
		// cars.add(new Person("test"));
		bean.setCars(cars);
		JSONObject jsonObject = JSONObject.fromObject(bean);
		System.out.println("testBeadToJSON---jsonObject----" + jsonObject);

	}

	@Test
	/**
	 * 将json字符串转换为对象
	 * @throws Exception
	 */
	public void testJSONToObject() throws Exception {
		String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
		JSONObject jsonObject = JSONObject.fromObject(json);
		Object bean = JSONObject.toBean(jsonObject);
		assertEquals(jsonObject.get("name"),
				PropertyUtils.getProperty(bean, "name"));
		assertEquals(jsonObject.get("bool"),
				PropertyUtils.getProperty(bean, "bool"));
		assertEquals(jsonObject.get("int"),
				PropertyUtils.getProperty(bean, "int"));
		assertEquals(jsonObject.get("double"),
				PropertyUtils.getProperty(bean, "double"));
		assertEquals(jsonObject.get("func"),
				PropertyUtils.getProperty(bean, "func"));

		List arrayList = (List) JSONArray.toCollection(jsonObject
				.getJSONArray("array"));
		for (Object object : arrayList) {
			System.out.println(object);
		}

	}
}

处理嵌套json格式的数据。。。 public static void main(String[] args) { // 官方API http://www.json.org/java/ /* 购物车中信息 goods_cart={cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}}; * **/ try{ String s0 = "{cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}};"; String s= java.net.URLDecoder.decode(s0, "utf-8"); System.out.println(s); JSONObject o = new JSONObject(s); System.out.println(o.get("cart_1325036696007")); //根据属性,获取值 System.out.println(o.toString()); //得到字符串 System.out.println(o.names().get(2)); //获取对象中第三组属性名 System.out.println(o.names().length()); //获取对象中属性个数 //System.out.println(o.names().getJSONArray(1)); //获取对象中属性个数 //names(jsonObjectName) 私有方法 获取该对象的所有属性名,返回成JSONArray。 //JSONObject.getNames(jsonObjectName) 静态方法 获取对象的所有属性名,返回成数组。 System.out.println(JSONObject.getNames(o.getJSONObject("cart_1325036696007"))[1]); System.out.println(o.getJSONObject("cart_1325036696007").names().get(1)); System.out.println(o.length()); //共有几组对象 System.out.println(o.has("cart_1325036696007")); //有无该该值 /* 遍历json中的每一组元素*/ String name = null; JSONObject t_o = null; for(int i=0; i<o.length(); i++){ name = JSONObject.getNames(o)[i]; System.out.println("商品项ID:"+name); t_o = o.getJSONObject(name); for(int j=0; j< t_o.length(); j++){ name = JSONObject.getNames(t_o)[j]; System.out.print(name+":"+t_o.get(name)+" "); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值