文档
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<version>5.8.10</version>
</dependency>
为了避免字符串中各种转义字符,我们采用直接从文件中读取json字符串的方式
data.json
{
"name": "Tom",
"age": 23
}
实体类
package com.github.mouday.demo;
public class User {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
使用示例
package com.github.mouday.demo;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.io.File;
import java.nio.charset.Charset;
public class Demo {
public static void main(String[] args) {
JSONObject json = JSONUtil.readJSONObject(new File("./data.json"), Charset.forName("utf-8"));
User user = json.toBean(User.class);
System.out.println(user.getName()); // Tom
System.out.println(user.getAge()); // 23
}
}