【原】JSON

作者:david_zhang@sh 【转载时请以超链接形式标明文章】

https://www.cnblogs.com/david-zhang-index/p/16991324.html

序列化:既java对象转json,String objJson = JSON.toJSONString(Objet obj);

1,将map转json

public class TestJson {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1","one");
        map.put("key2","two");
        String jsonStr = JSON.toJSONString(map);
        System.out.println(jsonStr);
    }
}
{"key1":"one","key2":"two"}

 2,自定义java bean转json

public class TestJson {
    public static void main(String[] args) {
        Order o1 = new Order("t1", "100.5", "1000", "", "guoli", "bid");
        String jsonStr = JSON.toJSONString(o1);
        System.out.println(jsonStr);
    }
}
{"bargainFlag":"","mdEntryPx":"100.5","mdEntrySize":"1000","mdEntryType":"bid","settleType":"t1","venue":"guoli"}

3,json转list

String s1 = "[{\"age\":3,\"birthdate\":1496738822842,\"name\":\"校长\",\"old\":true,\"salary\":123456789.0123}]";
List<Conf> confList = JSONArray.parseArray(s1, Conf.class);

4,list转json

List<Student> students = new ArrayList();
String str = JSON.toJSONString(students);

反序列化:既json对象转java,User user1 = JSON.parseObject(userJson, User.class);

1,将字符串反序列化成java bean

public class TestJson {
    public static void main(String[] args) {
        String jsonStr = "{\"bargainFlag\":\"\",\"mdEntryPx\":\"100.5\",\"mdEntrySize\":\"1000\",\"mdEntryType\":\"bid\",\"settleType\":\"t1\",\"venue\":\"guoli\"}";
        Order o2 = JSON.parseObject(jsonStr, Order.class);
        System.out.println(o2.toString());
    }
}
Order(settleType=t1, mdEntryPx=100.5, mdEntrySize=1000, bargainFlag=, venue=guoli, mdEntryType=bid)

2,泛型反序列化,json转map

public class TestJson {
    public static void main(String[] args) {
        String jsonStr = "{\"key1\":\"one\",\"key2\":\"two\"}";
        Map map = JSON.parseObject(jsonStr);
        System.out.println(map.get("key1"));
    }
}

 

posted @ 2022-12-19 00:42  david_zhang@sh  阅读(9)  评论(0编辑  收藏  举报