Java中List集合和JSON对象之间的相互转换
阅读原文时间:2021年04月20日阅读:1

第一种方法:

代码实现

/**
     *数据封装成json
     *
     * @param items 物料入库数据
     * @return json
     * @throws JSONException
     */
public static String GoodIn2Json(List<GoodInfo> 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<MoreInfo> Json2UserDefine(String data) throws JSONException {
        List<MoreInfo> 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<Person> persons = new ArrayList<Person>();  
String str = gson.toJson(persons);  

//json转换为list
Gson gson = new Gson();  
List<Person> persons = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType()); 

第三种方法:

导入阿里的fastJson.jar

//list转换为json
List<CustPhone> list = new ArrayList<CustPhone>();
String str=JSON.toJSON(list).toString();

//json转换为list
List<Person> list = new ArrayList<Person>();  
list = JSONObject.parseArray(jasonArray, Person.class); 

完!!!