我很难解析我从Web服务器获取的JSON响应。以下是我正在使用的相关代码:
获取JSON响应的方法:
void readResponse(String response)
{
Log.w("Rakshak", "In the in the new user: "+response); <-- log entry posted below
Gson gson = new Gson();
NewUserModel newUser = gson.fromJson(response, NewUserModel.class);
Toast.makeText(this, newUser.firstName, Toast.LENGTH_SHORT).show(); <-- this dosent show
Log.w("Rakshak", newUser.getFirstname());<-- no log entry here
Log.w("Rakshak", newUser.firstName); <-- no log entry here
}
“readResponse”方法第一行的日志:
05-20 19:56:10.963: W/Rakshak(8519): In the in the new user: {"id":18,"username":"Rakshak","password":"[password]","firstName":"Rakshak","lastName":"Raghavan","created":"2014-05-20T14:26:10+0000","updated":null}
现在是NewUserModel类:(这是我认为问题所在的地方)
public class NewUserModel {
public String id;
public String created;
/*
* All the set methods
*/
@Expose
@SerializedName("username")
public String username;
public void setUsername(String s)
{
this.username = s;
}
@Expose
@SerializedName("password")
public String password;
public void setPassword(String s)
{
this.password = s;
}
@Expose
@SerializedName("firstName")
public String firstName;
public void setFirstName(String s)
{
this.firstName = s;
}
@Expose
@SerializedName("lastName")
public String lastName;
public void setLastName(String s)
{
this.lastName = s;
}
/*
* All the get methods
*/
public String getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
public String getFirstname() { return firstName; }
public String getLastname() { return lastName; }
public String getCreated() { return created; }
}
为什么我不能从JSON中获取东西?在NewUserModel newUser = gson.fromJson(response, NewUserModel.class);
之后没有做任何事情的Toast和2 log。有人可以告诉我我做错了吗?
答案 0 :(得分:2)
使用GSON Library时,我也遇到了这种错误。
你可以这样试试。Type modelType = new TypeToken<NewUserModel>() {}.getType();
NewUserModel newUser = gson.fromJson(response, modelType);
希望它有所帮助。