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);
}