net.sf.json解析字符串(自定义类)
2018-07-24 本文已影响0人
jarWorker
json-lib-2.3-jdk15.jar
commons-beanutils.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
Man类
package test;
public class Man {
//属性和json的键对上
private String name;// 姓名
private String sex;// 性别
private Integer age;// 年龄
private String goodAt;// 特长
public Man() {
super();
}
public Man(String name, String sex, Integer age, String goodAt) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.goodAt = goodAt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGoodAt() {
return goodAt;
}
public void setGoodAt(String goodAt) {
this.goodAt = goodAt;
}
}
测试用例
package test;
import org.junit.Test;
import net.sf.json.JSONObject;
public class test {
@Test
public void netSfJson() {
String json = "{\r\n" + "\"name\":\"jarWorker\",\r\n" + "\"sex\":\"男\",\r\n" + "\"age\":26,\r\n"
+ "\"goodAt\":\"Java\"}";
String jsonStr = "{\r\n" + "\"name\":\"jarWorker\",\r\n" + "\"sex\":\"男\",\r\n" + "\"age\":26,\r\n"
+ "\"love\":[{\"hobby\":\"足球\",\"color\":\"White\"},{\"hobby\":\"篮球\",\"color\":\"Brown\"},{\"hobby\":\"简书\",\"color\":\"Yellow\"}],\r\n"
+ "\"goodAt\":\"Java\"\r\n" + "}";
JSONObject jsonObjectBean = JSONObject.fromObject(json);
Man man = (Man) JSONObject.toBean(jsonObjectBean, Man.class);
//JSONObject jsonObject = JSONObject.fromObject(jsonStr);
// 存在json数组love:man1无法转换,目前找不到如何破解
//Man man1 = (Man) JSONObject.toBean(jsonObject, Man.class);
String manName = man.getName();
String manSex = man.getSex();
Integer manAge = man.getAge();
String manGoodAt = man.getGoodAt();
System.out.println("manName===" + manName);
System.out.println("manSex===" + manSex);
System.out.println("manAge===" + manAge);
System.out.println("manGoodAt===" + manGoodAt);
}
}
Console:输出
manName===jarWorker
manSex===男
manAge===26
manGoodAt===Java