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?
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?"
ObjectNode.Properties.Map.Jackson can handle all of those.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With