1

I have a flat json array which look like this :

[
  {
    "homeID": "ID1",
    "homeName": "David",
    "childID": "ID1",
    "childName": "AAAA"
  },
  {
    "homeID": "ID1",
    "homeName": "David",
    "childID": "ID2",
    "childName": "AAAAA"
  },
  {
    "homeID": "ID2",
    "homeName": "CASEY",
    "childID": "ID1",
    "childName": "AAAA"
  },
  {
    "homeID": "ID2",
    "homeName": "CASEY",
    "childID": "ID2",
    "childName": "AAAAA"
  }
]

Now what i need to do is to decode this JSONARRAY to a List of list<HOME> and in this list of HOMES I have a list list<CHILD>

my Bean class :

public class Home{
    private String homeName;
    private list<CHILD>;

    public Home(){}
}

public class Child{
    private String childName;

    public Child(){}
}

So what's the best practice to do this mapping with Jackson JSON lib and java 8 ?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
azelix
  • 1,257
  • 4
  • 26
  • 50

2 Answers2

2

I think GSON is what you are looking for, it's a Java API that can read/write from/to JSON in Java, it takes JSON as input and converts it to Java objects.

You will need to write something like:

String jsonInString = "{'homeName' : 'home1', 'children': [{'childName': 'child1'}]}";
Home h= gson.fromJson(jsonInString, Home.class);

It will give you a Home object, you will just edit it to read a List<Home>.

It will be something like:

Type listType = new TypeToken<List<Home>>() {}.getType();
List<Home> yourList = new Gson().fromJson(yourJSONString, listType);

This will give you what you are looking for.

You can refer to this gson tutorial and the answer here for further details and reading.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

I think custom deserializers is what you are looking for:

@JsonDeserialize(using = HomeDeserializer.class)
public class Home {
    private String homeName;
    private List<Child> childs;

    public Home(String homeName, String childName) {
        this.homeName = homeName;
        this.childs = Arrays.asList(new Child(childName));
    }

    // additional constructors
}

public class Child {
    private String childName;

    public Child(String childName) {
        this.childName = childName;
    }

    // additional constructors
}

public class HomeDeserializer extends JsonDeserializer<Home> {

    @Override
    public Home deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        ObjectNode node = p.readValueAsTree();

        JsonNode homeName = node.get("homeName");
        JsonNode childName = node.get("childName");

        return new Home(homeName.asText(), childName.asText());
    }

}
schrieveslaach
  • 1,689
  • 1
  • 15
  • 32