プロジェクトを開発したときに、Android アクティビティでエラーが発生しました
asp Webメソッドから返されるjson文字列は正しく返されますが、jsonをクラスに変換すると、クラスはnullに等しくなります(Google json jar 2.1で変換します)
android code:
//to call my service and get data
ServiceCall call = new ServiceCall();
String jsonuserdata = call.getUserData("abced@myservice.com")
.toString();
Toast.makeText(getApplicationContext(), jsonuserdata,Toast.LENGTH_SHORT).show();
//this Toast message is print data correctly
Gson gson = new Gson();
Type userType = new TypeToken<UserData>(){}.getType();
UserData user = gson.fromJson(jsonuserdata,userType);
Toast.makeText(getApplicationContext(), "" + user.userid.toString(),
Toast.LENGTH_SHORT).show();
問題は、json文字列をクラスに変換するときです
asp.net Web メソッドは有効な json 文字列を Android メソッドに返します
[WebMethod]
public string getUserData(string email)
{
UserData user = new UserData();
user = DataBase.getUserData(email);
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(user);
return strJSON;
}
これはJavaの私のクラスです
public class UserData {
public static Class<UserData> USERDATA_CLASS = UserData.class;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
String username;
String email;
String password;
String userid;
public UserData() {
}
public UserData(String id, String name, String age, String weight,
String height, String calorie, String status, String gender,
String idealweight, String minidealweight, String maxidealweight,
String email, String password, String country, String report,String accountstatus) {
this.userid = id;
this.username = name;
this.email = email;
this.password = password;
}
public UserData(UserData user) {
this.userid = user.userid;
this.username = user.username;
this.email = user.email;
this.password = user.password;
}
}