将JSON数据解析转换为样例对象
时间: 2024-04-29 15:20:56 浏览: 56
假设有以下JSON数据:
```json
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
},
"phones": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
```
可以使用以下Java代码将其解析为样例对象:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class Example {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"Anytown\",\"state\":\"CA\"},\"phones\":[{\"type\":\"home\",\"number\":\"555-1234\"},{\"type\":\"work\",\"number\":\"555-5678\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(json, Person.class);
System.out.println(person);
}
}
class Person {
private String name;
private int age;
private Address address;
private Phone[] phones;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Phone[] getPhones() {
return phones;
}
public void setPhones(Phone[] phones) {
this.phones = phones;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
", phones=" + Arrays.toString(phones) +
'}';
}
}
class Address {
private String street;
private String city;
private String state;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "Address{" +
"street='" + street + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
'}';
}
}
class Phone {
private String type;
private String number;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return "Phone{" +
"type='" + type + '\'' +
", number='" + number + '\'' +
'}';
}
}
```
在这个例子中,我们使用了Jackson库来将JSON数据解析为Person对象。注意,Person类必须包含与JSON数据中的属性相对应的字段,以便Jackson可以正确解析数据。在这个例子中,Person类包含name、age、address和phones字段,分别对应JSON数据中的属性。Address和Phone类也是必需的,以便Person类可以包含嵌套属性。最后,我们使用toString方法打印解析的Person对象。
阅读全文