import org.json.JSONPropertyIgnore;
public class Person {
private String name;
private String about;
private int birthYear;
private String password;
public Person(String name, String about, int birthYear, String password) {
this.name = name;
this.about = about;
this.birthYear = birthYear;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
@JSONPropertyIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Person person = DataStore.getInstance().getPerson(name);
if (person != null) {
// String json = "{\n";
// json += "\"name\": " + JSONObject.quote(person.getName()) + ",\n";
// json += "\"about\": " + JSONObject.quote(person.getAbout()) + ",\n";
// json += "\"birthYear\": " + person.getBirthYear() + "\n";
// json += "}";
// response.getOutputStream().println(json);
JSONObject object = new JSONObject(person);
String jsonstring = object.toString();
System.out.println(jsonstring);
response.getOutputStream().println(jsonstring);
} else {
//That person wasn't found, so return an empty JSON object. We could also return an error.
response.getOutputStream().println("{}");
}
java对象完整属性输出:
{"password":"one","birthYear":1816,"name":"Ada","about":"Ada Lovelace was the first programmer."}
使用注解忽略password属性
@JSONPropertyIgnore
public String getPassword() {
return password;
}
java对象忽略部分属性输出:
{"birthYear":1815,"name":"Ada","about":"Ada Lovelace was the first programmer."}