JSON数据转换

来源:互联网 发布:在手机淘宝怎么搜店铺 编辑:程序博客网 时间:2024/05/16 04:08
关于JSON数据转换已经是很老的话题了,这里我们将又一次讨论JSON数据与Java对象的转换。
在http://www.json.org/上你可以发现一长串关于Java JSON的数据转换库:
org.json.
org.json.me.
Jackson JSONProcessor.
Json-lib.
JSONTools.
Stringtree.
SOJO.
Jettison.
json-taglib.
XStream.
Flexjson.
JONtools.
Argo.
jsonij.
fastjson.
mjson.
jjson.
json-simple.
json-io.
JsonMarshaller.
google-gson.
Json-smart.
FOSS NovaJSON.
这里先从最简单的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
0 0