0

Why is IACircle constructor not called?
This is how I load the Json ..

BufferedReader br = new BufferedReader(in);
LevelDefinition ld = new Gson().fromJson(br, LevelDefinition.class);

Json string ..

{
    "iaCircles": [
        {
            "x": -32.0,
            "y": -5.0,
            "angle": 0.0,
            "radius": 2.5,
            "density": 0.0,
            "friction": 0.0,
            "restitution": 1.0,
            "textureSelection": "CIRCLE",
            "inflictsDamage": true,
            "fixedRotation":true
        },
        {
            "x": 55.0,
            "y": -5.0,
            "angle": 0.0,
            "radius": 2.5,
            "density": 0.0,
            "friction": 0.0,
            "restitution": 1.0,
            "textureSelection": "CIRCLE",
            "inflictsDamage": true,
            "fixedRotation":true
        }
    ]
}

Java class parsed into ..

public class LevelDefinition {

    private Vector<IACircle> iaCircles;
}

IACircle definition ..

public class IACircle {
    public IACircle (
        float x, float y, float angle, float radius,
        float density, float friction, float restitution,
        String textureSelection, boolean inflictsDamage, boolean fixedRotation) { 
        System.out.println("constructor called, circle");
    }
}
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150

1 Answers1

2

You should define default no-args constructor for your class. GSON only calls no-args constructor to initialize a class. You have a constructor with arguments, that is why it is not called; it creates a ObjectConstructor to initizalize. Try this:

public class IACircle {
    public IACircle () { 
        System.out.println("constructor called, circle");
    }
}
jdiver
  • 2,228
  • 1
  • 19
  • 20
  • +1. Faster than me. See this question for more info: http://stackoverflow.com/questions/18645050/is-default-no-args-constructor-mandatory-for-gson – Enrichman May 21 '14 at 21:49
  • How come I can still execute `System.out.println(iaCircles.get(0).inflictsDamage);` and it outputs the value I provided in json? even though no-args constructor is called – bobbyrne01 May 21 '14 at 21:49
  • @bobbyrne01 If you do not provide the no-arg constructor, Gson will anyway find a way to create a class with the default constructor (no-arg) and create correctly the object. But you should provide it. – Enrichman May 21 '14 at 21:52