JSON数据转换

关于JSON数据转换已经是很老的话题了,这里我们将又一次讨论JSON数据与Java对象的转换。
在http://www.json.org/上你可以发现一长串关于Java JSON的数据转换库:
org.json.
org.json.me.
Jackson JSON Processor.
Json-lib.
JSON Tools.
Stringtree.
SOJO.
Jettison.
json-taglib.
XStream.
Flexjson.
JON tools.
Argo.
jsonij.
fastjson.
mjson.
jjson.
json-simple.
json-io.
JsonMarshaller.
google-gson.
Json-smart.
FOSS Nova JSON.
这里先从最简单的org.json开始,如果是Maven项目,引入jar包非常容易,详情请参考:  http://mvnrepository.com/artifact/org.json/json/20090211  当然你也可以在该站点上直接下载。

写一个简单的例子:关于JSON字符串转成Java最常见的List和Map的两个方法

package com.test.json;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONUtil {

public static List<</span>Map<</span>String, Object>> fromJSONStr2List(String jsonStr) throws JSONException {
JSONArray jsonArr = new JSONArray(jsonStr);
List<</span>Map<</span>String, Object>> list = new ArrayList<</span>Map<</span>String,Object>>();
for (int i=0; i<</span>jsonArr.length(); i++) {
JSONObject json2 = jsonArr.getJSONObject(i);
list.add(fromJSONStr2Map(json2.toString()));
}
return list;
}

public static Map<</span>String, Object> fromJSONStr2Map(String jsonStr) throws JSONException {
Map<</span>String, Object> map = new HashMap<</span>String, Object>();

JSONObject json = new JSONObject(jsonStr);
Iterator<</span>String> it = json.keys();
while (it.hasNext()){
String key = it.next();
Object value = json.get(key);
if (value instanceof JSONArray) {
List<</span>Map<</span>String, Object>> list = new ArrayList<</span>Map<</span>String,Object>>();
JSONArray jsonArr2 = ((JSONArray)value);
for (int i=0; i<</span>jsonArr2.length(); i++) {
JSONObject json2 = jsonArr2.getJSONObject(i);
list.add(fromJSONStr2Map(json2.toString()));
}
map.put(key.toString(), list);
} else {
map.put(key.toString(), value);
}
}
return map;
}

public static void main(String[] args) throws Exception {
List<</span>Map<</span>String, Object>> list = JSONUtil.fromJSONStr2List("[{\"name\":\"Richard\",\"age\":7},{\"name\":\"Susan\",\"age\":4}]");
System.out.println(list.get(0).get("name"));
Map<</span>String, Object> map = JSONUtil.fromJSONStr2Map("{\"name\":\"Richard\",\"age\":7}");
System.out.println(map.get("name"));
}

}


测试结果:

Richard
Richard
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值