Irrational error with gson library

edited September 2014 in Library Questions

I had some trouble with irration errors with object loaded from json using google gson library.

That's why I made simple test with loading objects. Everything works fine until i use random() in object method which I don't understand

big Big = null;
// some simple function which also produce errors
float avg(float m, float n) { float result = (m+n)/2; return result; } 

class big {
  float a;
  float b=1;
  big(float _a) {a = _a; }
  float Do(float _a, float _b) {
    a += _a + random(1,2); // << here is this MAGIC error
    b -= _b;
    return a+b;
  }
}

void setup()
{
  Gson gBig = new Gson();
  try {
    String File = "C:\\Users\\user\\Desktop\\file.json";
    BufferedReader br = new BufferedReader(new FileReader(File));
    Big = gBig.fromJson(br, big.class);
  } catch (IOException e) {
    e.printStackTrace(); }
}

What's the problem? line a += _a + random(1,2); produce "NullPointerException".

Also if you change it to a += _a + avg(1,2); it will produce error.

But change it to a += _a + max(1,2); - works FINE!

Can't figure out why my avg() and even built-in random() results in error.

Tagged:

Answers

  • Big = gBig.fromJson(br, big.class);

    Note that traditionally, the name of the class starts with an initial uppercase and the name of variables start with a lowercase char...

    That said, a potential issue might be this big.class, because big is (apparently) defined inside a .pde file, so its exact class name is something like Foo$big.class or similar, where Foo is the name of your sketch.
    Unless you put your class in its own .java file.

  • I think it doesn't matter whether class big is nested or not.
    Issuing println(big.class); gonna display "Class Foo$big" after all! :-B

    However, in order to access it, declare everything there public.
    Maybe you gotta declare that big class static too, so there's no need for an instance of the enveloping class!

  • edited September 2014

    Yeah, I was probably confusing with reflection where we specify the name of the class as string. Here, the compiler sorts out the issue.

    You should read on Gson way to handle classes. A library like Jackson prefers to have a class with a default constructor and defined setters for each field, to have a standard way to create and initialize it. Otherwise, we have to use special annotations for that.

    And the advice on making the class in its own .java file, or making it static (roughly the same thing) still stands.

Sign In or Register to comment.