类属性名大写的情况下,需要做些特殊配置才能正常将JSON文本值赋值给相应属性,可参考以下代码:
public class Person {
private String Name;
private int Age;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
@Override
public String toString() {
return "Name:"+this.Name+",Age:"+this.Age;
}
}
public class MyPropertyNameProcessor implements PropertyNameProcessor {
@Override
public String processPropertyName(Class beanClass, String name) {
return Introspector.decapitalize(name);
}
}
/**
* 测试普通类
*/
public static void testSimple(){
Random random = new Random();
JSONArray jsonArray = new JSONArray();
for(int i=0;i<10;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("Name","Nick:"+i);
jsonObject.put("Age",random.nextInt(i*10+1));
jsonArray.add(jsonObject);
}
JsonConfig jsonConfig = new JsonConfig();
//设置需要转换成对象的类
jsonConfig.setRootClass(Person.class);
MyPropertyNameProcessor propertyNameProcessor = new MyPropertyNameProcessor();
//JSON转换成对象的过程中,如果类属性名首字母大写需要使用自定义属性处理器
jsonConfig.registerJavaPropertyNameProcessor(Person.class,propertyNameProcessor);
Collection<Person> collection = JSONArray.toCollection(jsonArray, jsonConfig);
for (Person p:collection) {
System.out.println(p);
}
}
这里只是简单类的处理,嵌套类可以自行下载完整工程资源查阅