JSON Substitution Substitutions

I am looking for a Java library that can perform variable substitution when marshaling Json onto an object on the fly.

For example, the Json template will have variable substitution sites / placeholders, such as:

{ "User": { "Name": "${name}", "Age": ${age} } } 

which would result in a Java object representing the next time marshaled:

 { "User": { "Name": "Elvis", "Age": 80 } } 

I want something like this:

 ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(new File("c:\\user.json.template"), User.class, "Elvis", 80); 
+6
source share
2 answers

This is really not available for JSON libraries, since the JSON format itself does not have the support or concept of variable substitution. It is best to use a JSON library (e.g. Jackson) to get a tree view (for Jackson, which would be JsonNode ), then cross it and use another library to handle textual substitution. It can be a lot, from a stringtemplate to others (possibly the MessageFormat , which is referenced by another answer).

It is also possible to return something else if your substitutions are never funny “funny characters” (quotes, line feeds); if so, you can first use the templating lib template, the JSON parser for the next feed of the processed text. But this is a little risky, as usually one case ultimately arises when you end up trying to add a quote, say, and then the parsing fails.

0
source

Maybe a MessageFormat object from the apache community can help? Here is an example: http://examples.javacodegeeks.com/core-java/text/messageformat/java-messageformat-example/

-1
source

Source: https://habr.com/ru/post/981406/


All Articles