Press ESC to close

Java中List集合和JSON对象之间的相互转换

第一种方法:

代码实现

/**

*数据封装成json

*

* @param items 物料入库数据

* @return json

* @throws JSONException

*/

public static String GoodIn2Json(List items) throws JSONException {

if (items == null) return "";

JSONArray array = new JSONArray();

JSONObject jsonObject = null;

GoodInfo info = null;

for (int i = 0; i < items.size(); i++) {

info = items.get(i);

jsonObject = new JSONObject();

jsonObject.put(Api.COLORID, info.getColorId());

jsonObject.put(Api.STOCK, info.getStock());

array.put(jsonObject);

}

return array.toString();

}

/**

* 将json数组解析出来,生成自定义数据的数组

* @param data 包含用户自定义数据的json

* @return 自定义信息的数据

* @throws JSONException

*/

public static List Json2UserDefine(String data) throws JSONException {

List items = new ArrayList<>();

if (data.equals("")) return items;

JSONArray array = new JSONArray(data);

JSONObject object = null;

MoreInfo item = null;

for (int i = 0; i < array.length(); i++) {

object = array.getJSONObject(i);

String key = object.getString(Api.KEY);

String value = object.getString(Api.VALUE);

item = new MoreInfo(key, value);

items.add(item);

}

return items;

}

第二种方法:

导入谷歌的Gson.jar

//list转换为json

Gson gson = new Gson();

List persons = new ArrayList();

String str = gson.toJson(persons);

//json转换为list

Gson gson = new Gson();

List persons = gson.fromJson(str, new TypeToken>(){}.getType());

第三种方法:

导入阿里的fastJson.jar

//list转换为json

List list = new ArrayList();

String str=JSON.toJSON(list).toString();

//json转换为list

List list = new ArrayList();

list = JSONObject.parseArray(jasonArray, Person.class);

完!!!