Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON variable substitution placeholders

Tags:

java

json

jackson

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);
like image 317
DarVar Avatar asked Jan 22 '15 16:01

DarVar


People also ask

What is placeholder in JSON?

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.

Can you use variables in JSON?

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.


1 Answers

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.

like image 153
StaxMan Avatar answered Nov 12 '22 04:11

StaxMan