P
P
programmerjava2015-04-02 22:06:40
Java
programmerjava, 2015-04-02 22:06:40

Jackson POJO serialization. How to pull a single property from an encapsulated object?

There is an object of class A. It needs to be turned into json

class A {
private String id;
  private String descr;
  private B b;
}

And there is class B. It can be very large.
class B {
  private String id;
  ...
}

I wonder if it is possible to turn an object of class A into such a json - an object
{
  "id": "a_id",
  "b": {"id":"b_id"}
}

Is there an annotation that specifies the fields that need to be pulled out of an object of class B without affecting the rest @JsonXXXProperty({"id"}) ??? It would help a lot. At the same time (if there is one), I could separately convert an object of class B to json as it is marked with annotations in it.
I'm just starting to learn jackson. I would be very grateful for a hint.
upd
I just wanted to do this using annotations:
A a = ...
B b = ...
a.setB(b); b.setA(a);
ObjectMapper mapper = ...
String value = mapper.writeValueAsString(a);

after that value was supposed to store the json value:
{
"id": "a_id",
"b": {"id":"b_id"}
}

but for now, this is the code:
A a = ...
B b = ...
a.setB(b); b.setA(a);
ObjectMapper mapper = ...
ObjectNode node = (ObjectNode )mapper.convertValue(a, JsonNode.class);
node.remove(propertyToDelete);
String value = node.toString();

This part node.remove(propertyToDelete);can be very repetitive. depends on the number of fields to hide in json... not very convenient :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur, 2015-04-02
@timych

I did not understand you want to pull out the fields of class B without referring to the class itself? And you are not satisfied with:

A a  =  new A();
B b  =  new B();
a.setB(b);
// инициализирум поля и  преобразовываем в  JSON
...
// после парсинга из  JSON
String bId = a.getB().getId();

?
Or did I not understand the question?

E
Eugene, 2015-04-03
@zolt85

And what prevented you from the rest of the fields? I so understood on the client you all the same address only to b.id. The rest just ignore.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question