AdamM
AdamM

Reputation: 4440

Jackson Data binding model unmarshalling array of objects

Okay I have a JSON file and it has a set of objects that I wish to unmarshal into array of objects.

An example of how the JSON file is laid out is:

{
"data":{
  "name":{
     "fName":"John",
     "lName":"Doe"
  },
  "name":{
     "fName":"James",
     "lName":"Dokes"
  }
 }
}

The full JSON file is a lot more complex than this, this is just a example of how it is laid out.

What I want to do is to take those names, and unmarshall them into an array of name objects so I can access each name object whenever I want.

The classes are set up as

Test Class

 private Data data;

public void setData(Data d) {
    data = d;
}

public Data getData() {
    return data;
}

public String toString() {
    return "" + data;
}

Data Class

 private Name name;

public void setName(Name n){
    name = n;
}


public Name getName(){
    return name;
}


public String toString(){
    return "Names " + name;
}

Then the Name class is just

public class Name {

private String fName;
private String lName;

 //Getter setters here

    public String toString(){
    return "\nFirstName: " + fName + "\nLastName: " + lName;
}

Then in the main class, I just do

 ObjectMapper mapper = new ObjectMapper();

    Test test = mapper.readValue(new File("C:\\JSON\\test.json"),
            Test.class);
    System.out.println(test);

Now this will print out

Names 
FirstName: James
LastName: Dokes

But it ignores the first name object, i.e. John Doe. What I want is to take each of these name objects and place them in an ArrayList, that way I can access the information, and display it whenever I want.

What am I doing wrong here? I tried changing the JSON file and making the names into an array, and then changing the code in the Data class and making Names an Array of object Names, but got an error saying

 Can not deserialize instance of Data out of START_ARRAY token

Would anyone be able to point me in the right direction here, as have tried many different solutions, but no success.

Thanks in advance for any help

EDIT:

Should my JSON look like this then

 {
"data":{
   "name":[
      {
         "fName":"John",
         "lName":"Doe"
      },
      {
        "fName":"test",
        "lName":"test2"
     }
   ]
 }
}

Upvotes: 2

Views: 2073

Answers (1)

matt b
matt b

Reputation: 139931

What you posted isn't really valid JSON as the data object has two keys with the same value name. Or rather, this JSON doesn't represent an array of names as your title suggests it should.

If the JSON data is meant to be a true JSON object, meaning that it is similar to a hashtable of names to values, then you should represent than in your Java class as a Map. But your Test class has a single Data field, which has a single Name field. One instance of Test cannot have more than one Name in this structure.

Upvotes: 4

Related Questions