Interpolate JSON values into a string

落花浮王杯 提交于 2020-03-03 09:15:33

问题


I am writing an application/class that will take in a template text file and a JSON value and return interpolated text back to the caller.

The format of the input template text file needs to be determined. For example: my name is ${fullName}

Example of the JSON:

{"fullName": "Elon Musk"}

Expected output:

"my name is Elon Musk"

I am looking for a widely used library/formats that can accomplish this.

  1. What format should the template text file be?

  2. What library would support the template text file format defined above and accept JSON values?

Its easy to build my own parser but there are many edge cases that needs to be taken care of and I do not want to reinvent the wheel.

For example, if we have a slightly complex JSON object with lists, nested values etc. then I will have to think about those as well and implement it.


回答1:


I have always used org.json library. Found at http://www.json.org/.

It makes it really easy to go through JSON Objects.

For example if you want to make a new object:

JSONObject person = new JSONObject();
person.put("fullName", "Elon Musk");
person.put("phoneNumber", 3811111111);

The JSON Object would look like:

{
"fullName": "Elon Musk",
"phoneNumber": 3811111111
}

It's similar to retrieving from the Object

String name = person.getString("fullName");

You can read out the file with BufferedReader and parse it as you wish. Hopefully I helped out. :)




回答2:


This is how we do it.

Map inputMap = ["fullName": "Elon Musk"]
        String finalText = StrSubstitutor.replace("my name is \${fullName}", inputMap)




回答3:


You can try this: https://github.com/alibaba/fastjson

Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.



来源:https://stackoverflow.com/questions/56570582/interpolate-json-values-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!