字符串 {"meta":{"page":1,"limit":10000,"hasnext":false,"count":54},"data":[{"keepalive":30,"mailbox_len":0}]} 怎么转换成java对象
时间: 2024-04-15 07:22:51 浏览: 70
JSON字符串和java对象的相互转换
5星 · 资源好评率100%
要将字符串转换为Java对象,你可以使用JSON库来实现。在Java中,常用的JSON库有Jackson、Gson等。以下是使用Jackson库将该字符串转换为Java对象的示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"meta\":{\"page\":1,\"limit\":10000,\"hasnext\":false,\"count\":54},\"data\":[{\"keepalive\":30,\"mailbox_len\":0}]}";
try {
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
System.out.println(myObject);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyObject {
private Meta meta;
private Data[] data;
// getters and setters
@Override
public String toString() {
return "MyObject{" +
"meta=" + meta +
", data=" + Arrays.toString(data) +
'}';
}
}
class Meta {
private int page;
private int limit;
private boolean hasnext;
private int count;
// getters and setters
@Override
public String toString() {
return "Meta{" +
"page=" + page +
", limit=" + limit +
", hasnext=" + hasnext +
", count=" + count +
'}';
}
}
class Data {
private int keepalive;
private int mailbox_len;
// getters and setters
@Override
public String toString() {
return "Data{" +
"keepalive=" + keepalive +
", mailbox_len=" + mailbox_len +
'}';
}
}
```
在上述代码中,我们定义了与JSON字符串对应的Java类结构,并使用`ObjectMapper`类的`readValue`方法将JSON字符串转换为Java对象。你可以根据实际情况修改类的命名和字段类型。
阅读全文