0

当我开发我的项目时,我在 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;

    }

}
4

1 回答 1

0

您可以简单地通过以下方式解析类的实例:

Type userType = new TypeToken<UserData>(){}.getType();
UserData user = gson.fromJson(jsonuserdata,userType);

->

UserData user = gson.fromJson(jsonuserdata, UserData.class);

编辑添加解释:

取自这里

如果指定的对象是泛型类型,此方法很有用。对于非泛型对象,请改用 fromJson(String, Class)。

所以你不应该使用类型参数,而是使用类。

于 2012-04-06T12:20:36.117 回答