json-lib首字母大写的json串转javabean

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json-lib首字母大写的json串转javabean相关的知识,希望对你有一定的参考价值。

依赖jar:

commons-beanutils-1.9.3.jar?

commons-collections-3.1.jar

commons-lang-2.4.jar

commons-logging-1.2.jar

ezmorph-1.0.6.jar

json-lib-2.4-jdk15.jar

 

测试程序:

1、Person.java:

import java.util.List;

/**
* Created by Administrator on 2017/5/6.
*/
public class Person {
private int id;
private String name;
private List<Address> addresses;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Address> getAddresses() {
return addresses;
}

public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}

@Override
public String toString() {
return "Person{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", addresses=" + addresses +
‘}‘;
}
}

2、Address.java:
public class Address {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Address{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}

3、主函数

JsonConfig config=new JsonConfig();
config.setRootClass(Person.class);

Map<String,Class<?>> classMap = new HashMap<String,Class<?>>();
classMap.put("addresses", Address.class);
config.setClassMap(classMap);

PropertyNameProcessor lowerCasePropertyNameProcessor = new PropertyNameProcessor() {
@Override
public String processPropertyName(Class aClass, String s) {
return s.substring(0,1).toLowerCase() + s.substring(1);
}
};

config.registerJavaPropertyNameProcessor(Person.class, lowerCasePropertyNameProcessor);
config.registerJavaPropertyNameProcessor(Address.class, lowerCasePropertyNameProcessor);

//大写转bean小写
String jsonString = "{\"Id\":3,\"Name\":\"xiaoming\",\"Addresses\":[{\"Name\":\"xian\"}]}";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Person person = (Person) JSONObject.toBean(jsonObject, config);
System.out.println(person);

4、运行结果
Person{id=3, name=‘xiaoming‘, addresses=[Address{name=‘xian‘}]}
























































































以上是关于json-lib首字母大写的json串转javabean的主要内容,如果未能解决你的问题,请参考以下文章

FastJSONFastJson转换json字符串key的首字母小写变大写的解决办法

API Json 对具有大写属性首字母的 C# 对象的响应

javabean转json,json转javabean,json字段首字母大写

fastjson转换首字母要求大写的问题

踩了大坑 : go json.Marshal时,结构体字段需要大写

JAVA返回前端时候bean转json时首字母第二个字母大写会自动变成小写的问题