java - 如何从文件中读取 JSON 并用值替换对象?
问题描述
我需要从文件中读取 JSON 并替换几个对象。
例如,我有类 User.java
public class User {
String username;
String email;
String city;
String code;
}
和 JSON:
{
"variables":
{
"user":
{
"value":
{
"username": "$USERNAME",
"email": "$EMAIL",
"city": "$CITY"
}
}
}
}
我有两个问题:
- 如何从文件中读取 JSON?读取 JSON 将由 WebClient POST API 发送。
- 如何替换 $USERNAME、$EMAIL 和 $CITY?我不会硬编码它。我有注册表。当有人填写表格时,它将被替换为 $...
首先,我将 JSON 硬编码为字符串,但我需要从文件中读取它
class JSONClass {
static String toFormat(User user) {
String jsonUserRegister = "{\n" +
" \"variables\":\n" +
" {\n" +
" \"user\": \n" +
" {\n" +
" \"value\":\n" +
" {\n" +
" \"username\": \"" + user.getUsername() + "\",\n" +
" \"email\": \"" + user.getEmail() + "\",\n" +
" \"city\": \"" + user.getCity() + "\",\n" +
" \"code\": \"" + user.getCode() + "\"\n" +
" } }\n" +
" }\n" +
"}";
return jsonUserRegister;
解决方案
这可以使用 Spring Boot 设置后端以接收客户端调用来实现。所以要让任务 1a 工作,我们需要下面
@RestController
public class JsonReaderController {
@Autowired
private ResourceLoader resourceLoader;
@PostMapping(value = "/read-json")
public String fileContent() throws IOException {
return new String(Files.readAllBytes(
resourceLoader.getResource("classpath:data/json- sample.json").getFile().toPath()));
}
}
上面的代码只是读取文件内容并作为字符串返回。注意默认响应是 Json。
现在我们已经完成了后端,我们需要任务 1b - 发送 POST 请求。
private String readJsonFile() throws IOException {
final OkHttpClient client = new OkHttpClient();
final String requestUrl = "http://localhost:8080/read-json";
Request request = new Request.Builder()
.url(requestUrl)
.post(RequestBody.create(JSON, ""))
.build();
try (Response response = client.newCall(request).execute()) {
//we know its not empty given scenario
return response.body().string();
}
}
readJsonFile方法发出一个 POST 请求 - 使用 OkHttp 到我们的后端位(在任务 1a 中完成)并将文件的内容作为 json 返回。
对于任务 2 -将 $USERNAME、$EMAIL 和 $CITY 替换为适当的值。为此,我们将使用 Apache commons-text 库。
public static void main(String[] args) throws IOException {
String fileContent = new ReadJsonFromFile().readJsonFile();
User user = new User("alpha", "alpha@tesrt.com", "Bristol", "alpha");
Map<String, String> substitutes = new HashMap<>();
substitutes.put("$USERNAME", user.getUsername());
substitutes.put("$EMAIL", user.getEmail());
substitutes.put("$CITY", user.getCity());
substitutes.put("$CODE", user.getCode());
StringSubstitutor stringSubstitutor = new StringSubstitutor(substitutes);
//include double quote prefix and suffix as its json wrapped
stringSubstitutor.setVariablePrefix("\"");
stringSubstitutor.setVariableSuffix("\"");
String updatedContent = stringSubstitutor.replace(fileContent);
System.out.println(updatedContent);
}
希望这可以帮助。
推荐阅读
- react-native - 如何在反应导航中自定义 tabBarComponent 的样式
- docker - 一个容器里面可以有其他容器吗?
- wordpress - 将 ACF 日期与今天的日期进行比较
- c# - 无法在 dot net core 应用程序中调用外部 API(POST 方法)
- java - Retrofit2 不发送 POST 数据
- r - 使用 gsub 替换字符串并跟随 n 个单词
- git - Git推送强制更新分支
- sas - 基本上需要减去base sas(proc sql)中的两个数据集
- angular - Angular httpclient 不使用绝对网址
- python-3.x - 从文本文件中快速读取数据