java 中用json-lib可以把json字符串直接封装成对象吗
{"person":[{"id":1,"name":"zpq","password":"123456"}],"head":{"result":1,"msgType":23}}
head类
public class Head {
private int msgType;
private int result;
public Head(){}
public int getMsgType() {
return msgType;
}
public void setMsgType(int msgType) {
this.msgType = msgType;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
User类
public class User {
private int id;
private String name;
private String password;
public User(){}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserJson类
public class UserJson {
private Head head;
private List<User> person;
public UserJson(){}
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public List<User> getPerson() {
return person;
}
public void setPerson(List<User> person) {
this.person = person;
}
}
public static void main(String[] args) {
User user = new User();
user.setId(1);
user.setName("zpq");
user.setPassword("123456");
List<User> list = new ArrayList<User>();
list.add(user);
Head head = new Head();
head.setResult(1);
head.setMsgType(23);
UserJson uj = new UserJson();
uj.setHead(head);
uj.setPerson(list);
String json = getJson(uj);
String j = json.substring(1,json.length()-1);
System.out.println(j);
//System.out.println(json);
//解析json字符串
JSONObject object = JSONObject.fromObject(j);
JSONArray person = object.getJSONArray("person");
JSONObject info = person.getJSONObject(0);
System.out.println(info.get("id"));
System.out.println(info.getString("name"));
System.out.println(info.get("password"));
JSONObject head1 = object.getJSONObject("head");
System.out.println(head1.get("result"));
System.out.println(head1.get("msgType"));
//System.out.println(jArray);
}
//将对象转为json字符串
public static String getJson(UserJson uj){