Conversion between Java String object Json

  

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

————————————————————————————————————————
static void main public (String [] args) { 
        // java achieve conversion between the object and the Json string 

        // convert between the Person object 1. JSON 
        //1.1 the Person object into a JSON 
        Person Person new new = P (10 "John Doe"); 
        Object obj = JSONArray.toJSON (P); 
        String = obj.toString JSON (); 
        System.out.println ( "the Person object into a JSON:" + JSON); 
        
        //1.2 the json string converted to the Person object 
        Person Person = JSONArray.parseObject (json, Person.class); 
        System.out.println ( "person.getName ():" + person.getName ()); 

        // 2. the List conversion between <Person> and JSON 
        //2.1 the List <Person> converted to JSON 
        List <Person> = new new personList the ArrayList <> (); 
        personList.add (new Person (10, "Joe Smith"));
        personList.add (new Person (10, "John Doe")); 
        personList.add (new Person (10, "Wang Wu")); 
        Object obj2 = JSONArray.toJSON (personList); 
        String json2 = obj2.toString () ; 
        System.out.println ( "the List <Person> turn into json:" + json2); 
        
        // 2.2 json string will turn into a List <Person> objects. 
        List <Person> List = JSONArray.parseArray (json2, the Person .class); 
        System.out.println ( "list.size ():" + list.size ()); 

        // 3. Map the transition between the object and the JSON 
        // 3.1 Map will turn into JSON 
        Map <String , the Person> = new new Map the HashMap <> (); 
        map.put ( ". 1", new new the Person (10, "Joe Smith")); 
        map.put ( "2", the Person new new (10, "John Doe"));
        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());

    }

Guess you like

Origin www.cnblogs.com/pxzbky/p/12163161.html