1. 有如下json 数据,自己定义合适的java类,将json 转换成java 对象并打印 { "username": "zs", "age": 20, "userDetail": { "address": "北京朝阳", "havHouse": true, "havCar": true }, "contacts": [{ "phoneNumber": "110", "contactName": "小红" }, { "phoneNumber": "12323213", "contactName": "小明" } ] }
时间: 2023-07-06 19:34:48 浏览: 174
Java中使用Json的net.sf.json包
5星 · 资源好评率100%
可以定义以下 Java 类来表示该 JSON 数据:
```java
public class User {
private String username;
private int age;
private UserDetail userDetail;
private List<Contact> contacts;
// getters and setters
}
public class UserDetail {
private String address;
private boolean havHouse;
private boolean havCar;
// getters and setters
}
public class Contact {
private String phoneNumber;
private String contactName;
// getters and setters
}
```
然后可以使用 JSON 解析库(如 fastjson)将 JSON 数据转换为 Java 对象,示例代码如下:
```java
String jsonStr = "{\"username\": \"zs\",\"age\": 20,\"userDetail\": {\"address\": \"北京朝阳\",\"havHouse\": true,\"havCar\": true},\"contacts\": [{\"phoneNumber\": \"110\",\"contactName\": \"小红\"},{\"phoneNumber\": \"12323213\",\"contactName\": \"小明\"}]}";
User user = JSON.parseObject(jsonStr, User.class);
System.out.println(user.getUsername());
System.out.println(user.getAge());
System.out.println(user.getUserDetail().getAddress());
System.out.println(user.getUserDetail().isHavHouse());
System.out.println(user.getUserDetail().isHavCar());
for (Contact contact : user.getContacts()) {
System.out.println(contact.getPhoneNumber());
System.out.println(contact.getContactName());
}
```
输出结果为:
```
zs
20
北京朝阳
true
true
110
小红
12323213
小明
```
阅读全文