I'm looking for a Java library that can do variable substitution when marshaling Json to an Object on-the-fly.
For example, the Json template would have variable substitution sites/placeholders like:
{
"User": {
"Name": "${name}",
"Age": ${age}
}
}
that would result in the Java Object representing the following once marshaled:
{
"User": {
"Name": "Elvis",
"Age": 80
}
}
What I want is something along the lines of this:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json.template"), User.class, "Elvis", 80);
JSON Placeholder is a fake REST API that is primarily used for prototyping and testing. You can call it a web developer's image placeholder. JSON Placeholder is an online service that can be used when you need fake data to prototype or test some fake data.
Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.
This is really out of scope for JSON libraries, since JSON format itself has no support or notion of variable substitution. Your best bet may be to use a JSON library (like Jackson) to get a tree representation (for Jackson that would be JsonNode
), then traverse it, and use another library for handling textual substitution. There are many that can do that, from stringtemplate
to others (perhaps MessageFormat
that other answer refers to).
It may also be possible to revert the other, if your substitutions will never funny "funny characters" (quotes, linefeeds); if so, you could use string templating lib first, JSON parser next feeding processed text. But it is bit riskier, as usually there is eventually one case where you do end up trying to add a quote, say, and then parsing fails.
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