Amar Mond
Amar Mond

Reputation: 195

Jackson Array of Objects

I have the following JSON:

[
  {
    "id": 3589954,
    "type": "e",
    "pos": 1
  },
  {
    "id": 3837014,
    "type": "p",
    "pos": 2
  }
]

and the following Java Class:

public class Business {

private int idBusiness;

private String type;

private int pos;

public Business(int idBusiness, String type, int pos) {
    this.idBusiness = idBusiness;
    this.type = type;
    this.pos = pos;
}

// getters & setters .........
}

and I am trying to read it as:

businessList = mapper.readValue(strBusinessIDArrayJSON, new TypeReference<List<Business>>(){});

I am not able to read the JSON - I get businessList = null after the call. What is the correct way to do this.

Upvotes: 0

Views: 248

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279950

I'm surprised you get null and not a bunch of exceptions. (I'll assume you are swallowing the exceptions.)

You need a no-argument constructor, or you need to annotate the parameters in your current constructor with @JsonProperty with the name of the JSON element to which they should map. It might look like

public Business(@JsonProperty("id") int idBusiness, @JsonProperty("type") String type,@JsonProperty("pos") int pos) {
    this.setId(idBusiness);
    this.type = type;
    this.pos = pos;
}

Note that the JSON contains the property id, not idBusiness, so you need a @JsonProperty("id") over the field, getter, or setter (or rename the field and its getter/setter).

Upvotes: 1

Thomas Junk
Thomas Junk

Reputation: 5676

You should name your property better:

private int id;

Alternatively you could use @JsonProperty(value="id") as annotation on your "idBusiness"

Upvotes: 1

Related Questions