Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jackson

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?

like image 290
Phate Avatar asked Mar 24 '14 17:03

Phate


2 Answers

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.

like image 131
Jason C Avatar answered Dec 17 '22 15:12

Jason C


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.

like image 28
fge Avatar answered Dec 17 '22 16:12

fge