This is the POJO:
public class MyPojo {
String id;
double myNumber;
}
This is my JSON:
{
"id": "id1",
"my_number": 10.0
}
This is my conversion code:
// from is the JSON String from Above
Map<String, Object> myData = gson.fromJson(new String(from, StandardCharsets.UTF_8), Map.class);
JsonElement jsonElement = gson.toJsonTree(myData); // I checked - this contains "myNumber: 10"
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class); // This contains "myNumber: 0"
myNumber
in the pojo
object is always 0
In my json I renamed it to myNumber
and that didn't work either.
Why is this happening and how do I fix it so that I don't lose the value of the int? Thanks
my_number
is not equal to myNumber
– meaning that the mapping is not correct in your case. You either have to configure the JSON name in the POJO (there is an annotation for that – @SerializedName), or you have to change the name of the attribute.
I prefer the first approach, so you change the POJO like this:
public final class MyPojo
{
String id;
@SerializedName( "my_number" )
double myNumber;
}