1

I have such structure of object:

class A {
    List<B> bees;
}

class B {
    String с;
}

I'm using Gson parser which serializes such object into this string:

{"a":{"bees":[{"с":"text"}]}}

(with adding a root element "a")

API's format is a little bit different:

{"a":{"bees":[{"b":{"с":"text"}}]}}

I need to be able to parse such strings into A objects correctly.

By default B object (as a part of A) becomes not null, but empty (all fields are null) which is understandable, cause parser doesn't find any field "b" in it (when it is actually a class name).

I'm looking for a general solution for that, I have a lot of such complex objects and I don't want to implement many custom deserializers for each of them.

Gson is not obligatory, I can use another lib if it's necessary.

Thanks.

a.toropov
  • 218
  • 2
  • 11

2 Answers2

2

I prefer Jackson Tree Model and JDK 8 Stream to parse such json string, the core idea is to map the bees array element {"b":{"с":"text"}} to {"с":"text"} by the functional map() API.

ObjectMapper mapper = new ObjectMapper();
JsonNode beesNode = mapper.readTree(jsonString).get("a").get("bees");
List<JsonNode> bs = StreamSupport.stream(beesNode.spliterator(), false)
                    .map(bee -> bee.get("b")).collect(Collectors.toList());
derek.z
  • 907
  • 11
  • 19
0

If it is possible for you to change the class structure then change the class structure so as to match the API's format. For example,

class A {
    List<B> bees;
}

class B {
    MyTypeObjB B;
}
class MyTypeObjB {
    String c;
}

EDIT As per the comments, you can also try to customize deserialize method by implementing JsonDeserializer interface on your custom class.
You can find detail information how it can be performed on,

Community
  • 1
  • 1
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
  • Well, I was thinking about it too. But it will increase number of classes in twice. Ideally I want to make it without any changes in bean classes structure (or with annotations or some extra field), to make it with some specific parser changes. – a.toropov Dec 26 '13 at 11:57
  • @a.toropov refer the edited answer and use custom `desrializer` if that can work and you can alter according to your need... – Deepak Bhatia Dec 26 '13 at 12:33