7

Currently I am doing something like that:

public class MyObject{
   public String name;
   //constructor here
}

So, if I serialize it:

ObjectMapper mapper = new ObjectMapper();
MyObject o = new MyObject("peter");
mapper.writeValue(System.out,o);

I get

{"name":"peter"}

I'd like to make this generic, so class would be:

public class MyObject{
  public String name;
  public String value;
  //constructor here
}

So that this call:

 ObjectMapper mapper = new ObjectMapper();
 MyObject o = new MyObject("apple","peter");
 mapper.writeValue(System.out,o);

would lead to

{"apple":"peter"}

is it possible?

Phate
  • 6,066
  • 15
  • 73
  • 138

2 Answers2

5

You seem to be asking for a way to store generically named properties and their values, then render them as JSON. A Properties is a good natural representation for this, and ObjectMapper knows how to serialize this:

ObjectMapper mapper = new ObjectMapper();

Properties p = new Properties();
p.put("apple", "peter");
p.put("orange", "annoying");
p.put("quantity", 3);
mapper.writeValue(System.out, p);

Output:

{"apple":"peter","orange":"annoying","quantity":3}      

While it's true that you can build ObjectNodes from scratch, using an ObjectNode to store data may lead to undesirable coupling of Jackson and your internal business logic. If you can use a more appropriate existing object, such as Properties or any variant of Map, you can keep the JSON side isolated from your data.

Adding to this: Conceptually, you want to ask "What is my object?"

  • Is it a JSON object node? Then consider ObjectNode.
  • Is it a collection of properties? Then consider Properties.
  • Is it a general a -> b map that isn't properties (e.g. a collection of, say, strings -> frequency counts)? Then consider another type of Map.

Jackson can handle all of those.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • @HotLicks Nothing at all, except `Properties` has a clear, self-documenting intention. But any old `Map` would get the job done, as far as pure functionality goes. Note that `Properties` implements `Map`. In any case, the real take-home point is to use a Jackson-independent object to store data. – Jason C Mar 24 '14 at 17:28
3

Instead of passing through POJOs, you can directly use Jackson's API:

private static final JsonNodeFactory FACTORY = JsonNodeFactory.instance;

//

final ObjectNode node = FACTORY.objectNode();
node.put("apple", "peter");
// etc

You can nest as many nodes you want as well.

fge
  • 119,121
  • 33
  • 254
  • 329