您的位置:首页 > Web前端 > JavaScript

JSON数据转换

2015-12-15 11:49 190 查看
关于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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: