Android 使用GSON库解析JSON时遇到问题
我很难解析来自web服务器的JSON响应。以下是我正在使用的相关代码位: 获取JSON响应的方法:Android 使用GSON库解析JSON时遇到问题,android,json,gson,Android,Json,Gson,我很难解析来自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.fromJso
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
}
现在是NewUserModel类:(我认为这就是问题所在)
为什么我不能从JSON上取东西?Toast和2个日志位于
NewUserModel newUser=gson.fromJson(响应,NewUserModel.class)之后代码>什么都不要做。有人能告诉我我做错了什么吗?我在使用GSON库时也遇到过这种类型的错误
你可以这样试试
Type modelType = new TypeToken<NewUserModel>() {}.getType();
NewUserModel newUser = gson.fromJson(response, modelType);
typemodeltype=newtypetoken(){}.getType();
NewUserModel newUser=gson.fromJson(响应,模型类型);
希望有帮助。您没有得到newUser从JSON()创建的对象。这行不是这样做的吗NewUserModel newUser=gson.fromJson(响应,NewUserModel.class);'还有其他我要做的事情吗?fromJson(stringJSON,typeOfT类型)-此方法将指定的json反序列化为指定类型的对象。第二个论点是类的类型。
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; }
}
Type modelType = new TypeToken<NewUserModel>() {}.getType();
NewUserModel newUser = gson.fromJson(response, modelType);