我刚注意到一些对我没有意义的事情。
请使用以下代码:
public class User {
private String name = "";
public User() {}
public static User fromJson(JSONObject json) {
User user = new User();
user.name = json.optString("name", "");
System.out.println("Name = " + user.getName());
// Will print: "Name = THEGIVENNAME"
return user;
}
public String getName() { return this.name; }
public String setName(String name) { this.name = name; }
}
如果我尝试访问User.fromJson
包之外的方法User
,当我执行user.getName()
时,它会返回一个空字符串:
public void someMethod() {
JSONObject json = new JSONObject();
try {
json.put("name", "Test Name");
} catch (JSONException e) { e.printStacktrace(); }
User user = User.fromJson(json);
System.out.println("Name = " + user.getName());
// Will print: "Name = "
}
但是,如果在User.fromJson
方法上我使用user.setName()
代替user.name =
,则可行:
...
public static User fromJson(JSONObject json) {
User user = new User();
user.setName(json.optString("name", ""));
return user;
}
...
然后:
public void someMethod() {
JSONObject json = new JSONObject();
try {
json.put("name", "Test Name");
} catch (JSONException e) { e.printStacktrace(); }
User user = User.fromJson(json);
System.out.println("Name = " + user.getName());
// Will print: "Name = Test Name"
}
我有什么东西在这里失踪吗?
谢谢。