java對象與Json字符串之間的轉化(fastjson)

1. 首先引入jar包java

在pom.xml文件里加入下面依賴:json

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

2. 建立一個Person類(方面下面使用)this

public class Person implements Comparable<Person> { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(int age, String name) { super(); this.age = age; this.name = name; } 
}

3.  實現java對象與Json字符串之間的轉化spa

public class Test { 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()); } }

運行以上代碼,打印結果爲:code

將Person對象轉成json:{"name":"張三","age":10}
person.getName():張三
將List<Person>轉成json:[{"name":"張三","age":10},{"name":"李四","age":10},{"name":"王五","age":10}]
list.size():3
將Map<String,Person>轉成json:{"1":{"name":"張三","age":10},"2":{"name":"李四","age":10},"3":{"name":"王五","age":10}}
person2.getName():張三xml

相關文章
相關標籤/搜索