使用json-lib将String类型的这字符中转成java对象

jiangbo578 发布于 2015/06/30 15:36
阅读 273
收藏 1

如下字符串使用json-lib怎样转成java对象:

{"from":"zh","to":"en","trans_result":[{"src":"\u7f51\u7edc\u771f\u5f3a\u5927","dst":"Really powerful network"}]}

加载中
0
公孙二狗
公孙二狗

"\u7f51\u7edc\u771f\u5f3a\u5927"

需要写程序自己转码

0
码上中国博客
码上中国博客
package src.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TestJson
{
    // json字符串转
    private static String diskListContent =
        "[{\"n1\":\"asd\",\"n2\":22,\"n3\":\"45.40GB\"," + "\"n4\":\"qwerty\",\"n5\":\"asd\",}," + "{\"n1\":\"local\","
            + "\"n2\":1,\"n3\":\"279.40GB\",\"n4\":\"ST3300656SS\",\"n5\":\"\\/devm\\/d0\"}]";

    /***
     * json字符串转java List
     * @param rsContent
     * @return
     * @throws Exception
     */
    private static List<Map<String, String>> jsonStringToList(String rsContent) throws Exception
    {
        JSONArray arry = JSONArray.fromObject(rsContent);

        System.out.println("json字符串内容如下");
        System.out.println(arry);
        List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < arry.size(); i++)
        {
            JSONObject jsonObject = arry.getJSONObject(i);
            Map<String, String> map = new HashMap<String, String>();
            for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();)
            {
                String key = (String) iter.next();
                String value = jsonObject.get(key).toString();
                map.put(key, value);
            }
            rsList.add(map);
        }
        return rsList;
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception
    {
        List<Map<String, String>> list1 = jsonStringToList(diskListContent);
        System.out.println("json字符串成map");
        for (Map<String, String> m : list1)
        {
            System.out.println(m);
        }
        System.out.println("map转换成json字符串");
        for (Map<String, String> m : list1)
        {
            JSONArray jsonArray = JSONArray.fromObject(m);
            System.out.println(jsonArray.toString());

        }
        System.out.println("list转换成json字符串");
        JSONArray jsonArray2 = JSONArray.fromObject(list1);
        System.out.println(jsonArray2.toString());
    }

}
上面的方法是使用json-lib.jar解决的

上面的方法是使用json-lib.jar解决的


返回顶部
顶部