• Java对象与Json字符串之间的转化


      

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.51</version>
    </dependency>

    ————————————————————————————————————————
    public static void main(String[] args) {
            // 实现java对象与Json字符串之间的转化
    
            // 1. Person对象与json之间的转换
            //1.1 将Person对象转成json
            Person p = new Person(10, "张三");
            Object obj = JSONArray.toJSON(p);
            String json = obj.toString();
            System.out.println("将Person对象转成json:" + json);
            
            //1.2 将json字符串转成Person对象
            Person person = JSONArray.parseObject(json, Person.class);
            System.out.println("person.getName():" + person.getName());
    
            // 2. 将List<Person>与json之间的转换
            //2.1 将List<Person>转成json
            List<Person> personList = new ArrayList<>();
            personList.add(new Person(10, "张三"));
            personList.add(new Person(10, "李四"));
            personList.add(new Person(10, "王五"));
            Object obj2 = JSONArray.toJSON(personList);
            String json2 = obj2.toString();
            System.out.println("将List<Person>转成json:" + json2);
            
            // 2.2. 将json字符串转成List<Person>对象
            List<Person> list = JSONArray.parseArray(json2, Person.class);
            System.out.println("list.size():" + list.size());
    
            // 3. 将Map对象与json之间的转换
            // 3.1 将Map转成json
            Map<String, Person> map = new HashMap<>();
            map.put("1", new Person(10, "张三"));
            map.put("2", new Person(10, "李四"));
            map.put("3", new Person(10, "王五"));
            Object obj3 = JSONArray.toJSON(map);
            String json3 = obj3.toString();
            System.out.println("将Map<String,Person>转成json:" + json3);
    
            // 3.2. 将json转成Map对象
            Map<String, Object> map2 = JSONArray.parseObject(json3);
            Person person2 = JSONArray.parseObject(map2.get("1").toString(), Person.class);
            System.out.println("person2.getName():" + person2.getName());
    
        }
  • 相关阅读:
    Leetcode:50. Pow(x, n)
    loj 2759「JOI 2014 Final」飞天鼠
    bzoj 3569 DZY Loves Chinese II
    CF407D Largest Submatrix 3
    bzoj 3837 pa2013 Filary
    bzoj 4722 由乃
    CF1105E Helping Hiasat
    loj 6043「雅礼集训 2017 Day7」蛐蛐国的修墙方案
    luogu P2605 [ZJOI2010]基站选址
    luogu P3226 [HNOI2012]集合选数
  • 原文地址:https://www.cnblogs.com/pxzbky/p/12163161.html
Copyright © 2020-2023  润新知