java 类型转换 json,string,map,list

2021-02-01  本文已影响0人  wyc0859

json转map

    public void a2(){
        String str = "{\"颜色\":\"红\",\"大小\":\"128\",\"price\":\"11\",\"stock_num\":\"22\"}";
        //第一种方式
        Map maps = (Map) JSON.parse(str);
        System.out.println("方式1: JSON类来解析JSON字符串");
        maps.forEach((k,v)->{
            System.out.println("k:" + k + "v:" + v);
        });
        System.out.println(maps);

        //第四种方式
        /**
         * JSONObject是Map接口的一个实现类
         */
        Map json = (Map) JSONObject.parse(str);
        System.out.println("方式2: JSONObject类的parse方法来解析JSON字符串");
        json.forEach((k,v)->{
            System.out.println("k:" + k + "v:" + v);
        });
        System.out.println(json);
    }

json转List

    public static  <T> List<T>  toList(String object,Class clazz){
        return JSONArray.parseArray(object, clazz);
    }
    public static  <T>  T  toObject(String object,Class clazz){
        return (T)JSONArray.parseObject(object, clazz);
    }
    public static <T> String toJsonString(List<T> list){
        return JSON.toJSONString(list);
    }
    public static <T> String toJsonString(T object){
        return JSON.toJSONString(object);
    } 

String strlist="[{\"颜色\":\"红\",\"大小\":\"128\",\"price\":\"11\",\"stock_num\":\"22\"},\n" +
            "{\"颜色\":\"红\",\"大小\":\"258\",\"price\":\"33\",\"stock_num\":\"44\"},\n" +
            "{\"颜色\":\"黄\",\"大小\":\"128\",\"price\":\"55\",\"stock_num\":\"66\"},\n" +
            "{\"颜色\":\"黄\",\"大小\":\"258\",\"price\":\"77\",\"stock_num\":\"88\"}]";
public void a3(){
        //1.test list  Json  String
        List<JSONObject> list = toList("[{\"id\":\"2222\",\"name\":\"n2222\"}," +
                "{\"id\":\"3333\",\"name\":\"n3333\"}]", JSONObject.class);
        System.out.println("String转list: "+
                list.get(0).get("name")+"@"+list.get(1).get("name"));

        //2.test  object Json String
        JSONObject obj=toObject("{\"id\":\"4444\",\"name\":\"n44444\"}", JSONObject.class);
        System.out.println("string转obj: "+obj.get("name"));

        List<JSONObject> list2 = toList(strlist, JSONObject.class);
        System.out.println(toJsonString(list2));

        //3.test list to  jsonstring
        List<JSONObject> objs=new ArrayList<>();
        JSONObject j5 = new JSONObject();
        j5.put("aa","5555");
        j5.put("bb","666");
        System.out.println(" obj 转 jsonstring: "+toJsonString(j5));
        objs.add(j5);
        System.out.println("list 转 jsonstring: " + toJsonString(objs));

        JSONObject j7 = new JSONObject();
        j7.put("cc","777");
        j7.put("dd","888");
        System.out.println("jsonstring: "+toJsonString(j7));
        objs.add(j7);
        System.out.println("jsonstring: "+toJsonString(objs));
    }

String转List

 String distance = "1.05,4.88,5.45,5.93,5.33";
 List<String> lis = Arrays.asList(distance.split(","));
上一篇下一篇

猜你喜欢

热点阅读