json轉換為Java對象
① 有沒有將json直接轉換生成java類的工具軟體
使用Jackson可以將json轉為Java對象,同樣也可以將java對象轉為json字元串,並且Spring框架內部也是使用的此jar。
實例:將json轉為java對象
/*
下面的id,name,age同是User實體類的屬性
*/
//將json轉為Java對象
Stringjson="{"id":1,"name":"張三","age":18}";
ObjectMappermapper=newObjectMapper();
Useruser=mapper.readValue(json,User.class);、
//將json轉為Java數組對象
Stringjson="[{"id":1,"name":"張三","age":18},{"id":2,"name":"李四","age":18},{"id":3,"name":"王五","age":18}]";
ObjectMappermapper=newObjectMapper();
User[]users=mapper.readValue(json,User[].class);
② json數組轉java對象怎麼轉
1、需要json的相關jar包
2、設置json格式字元串:
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
3、建立相應的類:
public class StudentList {
List<Student> student;
public List<Student> getStudent() {
return student;
}
public void setStudent(List<Student> student) {
this.student = student;
}
}
public class Student {
private String name;
private int age;
//private StudentClass studentClass;
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;
}
}
4、測試程序
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonToJavaBean {
public static void main(String[] args) {
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
Student stu = null;
List<Student> list = null;
try {
ObjectMapper objectMapper=new ObjectMapper();
StudentList studentList=objectMapper.readValue(str, StudentList.class);
list=studentList.getStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(Student s:list){
System.out.println(s.getName());
}
}
③ 怎麼將json對象轉換成一個java對象
public static void jsonStrToJava(){
//定義兩種不同格式的字元串
String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區\"}";
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區\"}]";
//1、使用JSONObject
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
//2、使用JSONArray
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//獲得jsonArray的第一個元素
Object o=jsonArray.get(0);
JSONObject jsonObject2=JSONObject.fromObject(o);
Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
System.out.println("stu:"+stu);
System.out.println("stu2:"+stu2);
}