前端之家收集整理的这篇文章主要介绍了
net.sf.json 属性 转换,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
需求分析: Person 的name属性和addresss属性在转换为json的时候 需转换为superman 和homeaddress。下面是相应的代码处理部分。
public class Person {
private String name;
private String address;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Person [name=" + name + ",address=" + address + ",password=" + password + "]";
}
}
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.PropertyNameProcessor;
import com.heavan.domain.Person;
public class JsonUtil {
public static void main(String[] args) {
//属性进行了映射
// address - homeaddress
// name - superman
String bean2Json = bean2Json();
System.out.println(bean2Json);
Person json2Bean = json2Bean(bean2Json);
System.out.println(json2Bean);
}
/**
* 从对象转换为json
* @return
*/
private static String bean2Json() {
Person person = new Person();
person.setAddress("山东");
person.setName("钓岛是中国的");
person.setPassword("美丽是大家的");
JsonConfig jsonConfig = new JsonConfig();
PropertyNameProcessor processor = new PropertyNameProcessor() {
@Override
public String processPropertyName(Class beanClass,String name) {
if(name.equals("name")){
return "superman";
}else if (name.equals("address")) {
return "homeaddress";
}
return name;
}
};
jsonConfig.registerJsonPropertyNameProcessor(Person.class,processor);
JSONObject jsonObject = JSONObject.fromObject(person,jsonConfig);
return jsonObject.toString();
}
/**
* 从json 转换为bean
* @param json
* @return
*/
private static Person json2Bean(String json) {
JsonConfig jsonConfig = new JsonConfig();
PropertyNameProcessor processor = new PropertyNameProcessor() {
@Override
public String processPropertyName(Class beanClass,String name) {
if (name.equals("homeaddress")) {
return "address";
} else if (name.equals("superman")) {
return "name";
}
return name;
}
};
jsonConfig.setRootClass(Person.class);
jsonConfig.registerJavaPropertyNameProcessor(Person.class,processor);
JSONObject jsonObject = JSONObject.fromObject(json,jsonConfig);
Person bean = (Person) JSONObject.toBean(jsonObject,jsonConfig);
return bean;
}
}
原文链接:https://www.f2er.com/json/290517.html