如何将json
文件绑定到object。
在这里,我使用 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;
}
}
这是针对详细信息数组的 的 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
文件的绑定类。
答案 0 :(得分:1)
请检查此解决方案是否有用。
我对 Root.java
进行了一些更改package com.test;
import java.util.ArrayList;
/**
*
* @author Ravi P
*/
public class Root {
ArrayList<Details> details;
public ArrayList<Details> getDetails() {
return details;
}
public void setDetails( ArrayList<Details> details ) {
this.details = details;
}
}
主要的java类是
package com.test;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
/**
*
* @author Ravi Palla
*/
public class Test {
static final String JSON_FILE = "C:\\tmp\\Details.json";
public static void main( String[] args ) {
try {
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().toArray( new Details[ root.getDetails().size() ] );
for ( Details memberDetails : details ) {
System.out.print( "name: " + memberDetails.getName() + ", " );
System.out.print( "age: " + memberDetails.getAge() + ", " );
System.out.println( "gender: " + memberDetails.getGender() );
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
输出为:
name: John, age: 27, gender: Male
name: Max, age: 27, gender: Male
name: esh, age: 27, gender: FeMale