Reputation: 4491
I'm trying to deserialize an error message I get from an api, this is my string:
{"Message":"Ya existe un usuario registrado con ese email"}
But when I call Gson like this it returns a NetworkError
with null values:
String message = new Gson().fromJson(jsonMessage, NetworkError.class).getMessage();
I have been looking at similar questions and realize there has to be something wrong in the NetworkError
class but I can't figure out what it is. Here is the class:
public class NetworkError {
private String message;
public NetworkError(final String message) {
this.message = message;
}
public String getMessage() { return message; }
}
I have tried by including a set method and an empty constructor but I still got null. Thanks
Upvotes: 0
Views: 2006
Reputation: 2211
Keys in JSON are case sensitive. Therefore, Gson is looking for the "message" key, which is not there (you are using the "Message" key).
You can just do:
@SerializedName("Message")
private String message;
Upvotes: 2
Reputation: 26007
Inside NetworkError.java
class, try changing your message
variable in the class to Message
, since that is the key you are receiving in the REST response and it might be causing issues when mapping the key.
I can understand that you still might want to use camel case for your variable names. You can use @SerializedName
annotation to keep your variable name anything you want but still have GSON map to it. You can read more on what is the basic purpose of @SerializedName annotation in android using GSon
Upvotes: 4