我有点难以理解如何做到最好并将我的 JASON 响应从 ASP.NET Web API 服务器映射到我的 Java 类中。
我使用此代码来请求服务器数据。
ClientResource res = new ClientResource(ADDRESS_URL + "/exed/students/");
Representation rep = res.get();
try {
Log.d(TAG, rep.getText());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
我成功地可以检索到这个 JSON 表示。
{"$id":"1","StudentId":1,"RowVersion":"AAAAAAAAB9M=","User":{"$id":"2","UserId":1,"Username":"1","Password":"1","UserTypeId":1,"FirstName":"George","LastName":"Taskos","RowVersion":"AAAAAAAAB9I=","Student":{"$ref":"1"},"Teacher":null,"UserType":null}}
现在我有了这些 Java 类。
用户。
public class User implements Serializable {
// Private fields
//
private int userId;
private String username;
private String password;
private int userTypeId;
private String firstName;
private String lastName;
private String userType;
private Timestamp rowVersion;
// Setters
// Getters....
}
和学生。
public class Student extends User implements Serializable {
// Private fields
private List<ClassType> classes;
private List<ExamTaken> examsTaken;
private Timestamp rowVersionStudent;
}
如何将表示检索到我的对象中。我已经看到了很多,我想我现在很头晕,无法找到解决方案。我不熟悉 Java 服务器端或任何东西,所以我想这就是为什么我对我在教程上读到的东西感到沮丧,我认为网站上缺少很多东西,或者没有清楚地解释。
任何简单的示例至少都将值取出并将它们放入我的对象中,就像我使用 SQLite 游标一样。响应的反序列化也非常棒:)
[编辑]
在原始建议之后,我最终得到了这段代码。
ClientResource res = new ClientResource(ADDRESS_URL + "/exed/students/");
Representation rep = res.get();
try {
JSONObject response = new JSONObject(rep.getText());
Log.d(TAG, rep.getText());
JSONObject user = response.getJSONObject("User");
Log.d(TAG, "User: " + user.toString());
JSONObject student = response.getJSONObject("Student");
Log.d(TAG, "Student: " + student.toString());
Log.d(TAG, "FirstName: " + user.getString("FirstName"));
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
但收到此消息的异常:异常:println 需要一条消息
Stacktrace 打印:异常:android.util.Log.println_native(Native Method)
未处理的异常是这样的:
03-06 13:07:14.668: ERROR/AndroidRuntime(25353): FATAL EXCEPTION: Thread-13908
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:155)
at com.tech.ed.data.access.WebServiceRepository$1.run(WebServiceRepository.java:74)
at java.lang.Thread.run(Thread.java:856)
我完全不明白是什么意思!
谢谢你。