JSON Return to JAVA Class Conversion Error

Asked

Viewed 94 times

3

I have a java class

public class PRODUTO extends SugarRecord implements Parcelable {

  private float id_pro;

  public PRODUTO(float id_pro){
    this.id_pro = id_pro;
  }

  public float getId_pro() {
    return id_pro;
  }
  public void setId_pro(float id_pro) {
    this.id_pro = id_pro;
  }
  // PARCELABLE
  public PRODUTO(Parcel parcel) {
    setId_pro(parcel.readFloat());
  }
  @Override
  public int describeContents() {
    return 0;
  }
  @Override
  public void writeToParcel(Parcel parcel, int i) {
    parcel.writeFloat(getId_pro());
  }
  ...
}

One API php that returns me one JSON of my base mysql, in it comes the id_pro, for example: 257895

But always add automatically one ".0" at the end of the variable AFTER ASSIGNING THE CLASS, thus: 257895.0

I already checked the return data, it comes right from JSON, but at the time of assigning the class is like this, in mysql base I have a field bigint that I’ve already switched to float also to test and did not give. However when I use String in the class for the id_pro, correctly receives 257895, but wanted to work directly in the object format.

Use a Httpurlconnection for the requisition.

Does anyone have any idea what I’m doing wrong?

1 answer

3


The float in Java represents a floating point number with 32-bit precision for every time you write the number, unless you’re doing something like a Console.WriteLine() with a format string, he will always write the .0 if you do not have decimal places to indicate that you do not actually have decimal places.

The solution will be to use a type of data that represents an integer number because in fact the ID is at all times an integer and for this purpose you can use either the int wants the long - or their Wrappers, Int and Long. Just keep in mind that in Java int uses 32 bits and the long uses 64, so the long despite spending more memory - easy to understand why it represents twice the bits of a int - also represents many, many more numbers:

 int | -2^31 a +2^31 -1 |             -2,147,483,648 a 2,147,483,647
long | -2^63 a +2^63 -1 | -9,223,372,036,854,775,808 a 9,223,372,036,854,775,807

Useful resources


Fun Fact: with a long, if your function makes an increment every nanosecond, it would take 292 years to overflow (!!!) source

  • Oops, thanks James, that’s right, as long he does not, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.