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

第一种方法:

代码实现

/**
     *数据封装成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);
  • 2
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值