如何将json
文件绑定到对象。这里我使用JSR-367 API,yasson实现来实现。
JSON 文件如下所示
{
"Details": [
{
"age": 27,
"gender": "Male",
"name": "John"
},
{
"age": 27,
"gender": "Male",
"name": "Max"
},
{
"age": 27,
"gender": "FeMale",
"name": "esh"
}
]
}
对于上面的 json,我创建了两个 Binding 类,它们
是针对json
.
1.
public class Details
{
private String name;
private int age;
private String gender;
private long phoneNumber;
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
这是针对Details数组
2)
public class Root
{
private Details[] details;
public Details[] getDetails() {
return members;
}
}
json
这是将类从文件绑定到对象的主要类
public class TestJsonB
{
static final String JSON_FILE = "/media/Resources/Details.json";
public static void main(String[] args) throws IOException
{
String content = new String(Files.readAllBytes(Paths.get(JSON_FILE)));
Jsonb jsonB = JsonbBuilder.create();
Root root = jsonB.fromJson(content,Root.class);
Details[] details = root.getDetails();
System.out.println(details);//null printing
}
}
帮助我为给定json
文件编写绑定类。