首页 > 解决方案 > 如何从文件中读取 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"
            } 
        }

    }

}

我有两个问题:

  1. 如何从文件中读取 JSON?读取 JSON 将由 WebClient POST API 发送。
  2. 如何替换 $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;

标签: javajson

解决方案


这可以使用 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);
}

希望这可以帮助。


推荐阅读