Fastjson是一個(gè)效率優(yōu)秀的Java JSON解析器,支持序列化和反序列化。當(dāng)一個(gè)JSON對(duì)象中存在嵌套的數(shù)組時(shí),F(xiàn)astjson可以將其轉(zhuǎn)成Java對(duì)象。
假設(shè)我們有一個(gè)JSON字符串:
{ "name": "Tom", "age": 18, "hobbies": ["reading", "sports"], "friends": [ { "name": "Jerry", "age": 20, "hobbies": ["music", "dance"] }, { "name": "Peter", "age": 22, "hobbies": ["swimming", "basketball"] } ] }
我們需要將其轉(zhuǎn)成Java對(duì)象。首先,我們需要定義Java類。注意,數(shù)組需要使用List類型。
public class Person { private String name; private int age; private List<String> hobbies; private List<Person> friends; // 省略getter和setter }
然后,我們可以使用Fastjson的API將JSON字符串轉(zhuǎn)成Java對(duì)象:
String jsonStr = "上面的JSON字符串"; Person person = JSON.parseObject(jsonStr, Person.class);
現(xiàn)在,我們可以獲取Java對(duì)象的屬性值,如:
String name = person.getName(); // "Tom" int age = person.getAge(); // 18 List<String> hobbies = person.getHobbies(); // ["reading", "sports"] List<Person> friends = person.getFriends(); Person friend1 = friends.get(0); String friend1Name = friend1.getName(); // "Jerry" int friend1Age = friend1.getAge(); // 20 List<String> friend1Hobbies = friend1.getHobbies(); // ["music", "dance"]
通過以上方法,我們可以將一個(gè)JSON字符串嵌套的數(shù)組轉(zhuǎn)成Java對(duì)象,使得我們可以方便地處理JSON數(shù)據(jù)。