如何从文件中读取JSON并用值替换对象?

问题描述 投票:1回答:1

我需要从文件中读取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;
java json
1个回答
0
投票

这可以使用Spring Boot来设置后端以接收客户端调用。因此,要使Task 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()));
  }
}

上面的代码只是读取文件内容并返回String。注意默认响应是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", "[email protected]", "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);
}

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.