发布网友 发布时间:2022-04-23 15:29
共3个回答
热心网友 时间:2023-07-20 03:01
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());
}
}
热心网友 时间:2023-07-20 03:01
看别人的:
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz);
}
return obj;
}
热心网友 时间:2023-07-20 03:02
如果你的json数组是字符串格式,可以使用
JSONObject obj = JSONObject.fromString(jsonStr);
然后你查看JSONObject 的api方法,它里面有getJSONArray()的方法,转数组。