Phate
Phate

Reputation: 6622

Is there a way to make a "generic" json object?

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?

Upvotes: 9

Views: 19681

Answers (2)

Jason C
Jason C

Reputation: 40386

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.

Upvotes: 5

fge
fge

Reputation: 121810

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.

Upvotes: 3

Related Questions