【问题标题】:Updating specific part of value in hash map dynamically动态更新哈希图中值的特定部分
【发布时间】:2019-12-11 12:27:47
【问题描述】:

我有一个带有 HTTP 发布请求处理程序的 Spring Boot 应用程序。它接受我解析的有效负载并输出 JSON。我已经处理它需要接受某些参数的有效负载(18)。

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;




@Validated
@RestController
public class MockController {


    @Autowired
    MockConfig mockconfig;

    private static final Logger LOGGER = LoggerFactory.getLogger(MockController.class);




    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "hello!";
    }
        String[] parse;
    @PostMapping(value = "/")
    public String payloader(@RequestBody String params ) throws IOException{
        LOGGER.debug("code is hitting");
        parse = params.split("\\|"); 
        String key;
        String value;
        String dyn;
        Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();

        if(parse.length!=18) {

            key = "Not_enough_parameters";
            value = predictionFeatureMap.get(key);
            Map<?, ?> resultJsonObj = new Gson().fromJson(value, Map.class);

        }
        else {
            key = params;
            value = predictionFeatureMap.get(key);
        }
        return value;
    }
}

我的配置类是我从文件中获取输入和输出并将它们放入哈希图中的地方。

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.springframework.context.annotation.Configuration;

@Configuration
public class MockConfig {
    private Map<String, String> predictionFeatureMap = new HashMap<String, String>();

    public Map<String,String> getPredictionFeatureMap() throws IOException {
        return predictionFeatureMap;
    }

    public MockConfig() throws IOException {
        init();
    }

    private Map<String, String> init() throws IOException {
        Scanner sc = new Scanner (new File("src/test/resources/Payload1.txt"));

        int counter = 1;
        String key = "";
        while (sc.hasNextLine()) {
            if(counter % 2 != 0) {
                key = sc.nextLine();
            }else {
                predictionFeatureMap.put(key, sc.nextLine());
            }
            counter++;
        }
        sc.close();
        return predictionFeatureMap;
    }




}

这是我正在尝试专门使用的文件中的键和值。

Not_enough_parameters
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:8", "version": "0.97", "coreName": "Patient_Responsibility"}

(JSON字符串是对参数过多或过少的响应......参数长度应该是18。)

示例输入:

ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0

这个输入会通过,因为它有 18 个参数...

我想要做的是如果用户卷曲例如 5 个参数

ncs|56-2629193|1972-03-28|20190218|77067

我希望值(JSON 错误消息)更新“实际”字段,如下所示:

{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:5", "version": "0.97", "coreName": "Patient_Responsibility"}

无需将其硬编码到 txt 文件或 hashmap 中...

我尝试获取字符串的索引并用 parse.length() 替换“8”字符并将其转换为 char 但它只是给了我这个输出:

{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting:1 actual:", "version": "0.97", "coreName": "Nulogix_Patient_Responsibility"}

如何解析或索引 JSON 以更新此值?或者有没有hashmap方法来处理这个?

【问题讨论】:

  • 我不得不阅读这篇文章 10 次,直到我隐约明白你想要做什么。但我还是不明白的东西。 Map&lt;?, ?&gt; resultJsonObj = new Gson().fromJson(value, Map.class); 您正在从地图中获取预定义的 json 键,然后使用 Gson 将其序列化为地图?这不是您在 Spring Boot 中错误处理的方式。
  • 我的建议,完全放弃Gson,Spring使用jackson,你抛出一个运行时异常并在@ControllerAdvice注释类中捕获它。在那里你会生成一个错误响应,然后返回给调用客户端。

标签: java json string spring-boot hashmap


【解决方案1】:

在使用框架时,您通常使用框架处理错误的方式来处理错误。

要处理 Spring Boot 中的错误,您通常会使用有助于处理错误的控制器建议。这是通过使用 @ControllerAdvice 注释类来创建的。

您可以在此处捕获抛出的异常并构建将返回给调用客户端的响应。

@PostMapping(value = "/")
public String payloader(@RequestBody String params ) throws IOException{
    LOGGER.debug("code is hitting");
    parse = params.split("\\|"); 
    String key;
    String value;
    String dyn;
    Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();

    if(parse.length!=18) {

        // Here you throw a custom runtime exception and pass what
        // parameters you want that will help you build your error 
        // message you are passing to your client.

        final String errorMessage = String.format(
            "Payload has incorrect amount of parts: expecting:%d actual:%d",
            predictionFeatureMap.size(), 
            parse.length);

        throw new MyException(errorMessage); 

    }
    else {
        key = params;
        value = predictionFeatureMap.get(key);
    }
    return value;
}

然后在控制器建议类中

@ControllerAdvice
public class Foo extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyException.class)
    public ResponseEntity<MyCustomErrorBody> handleControllerException(HttpServletRequest request, MyException ex) {

        // Build your error response here and return it. 
        // Create a class that will represent the json error body 
        // and pass it as body and jackson will deserialize it for 
        // you into json automatically.

        final MyCustomErrorBody body = new MyCustomErrorBody(false, ex.getMessage(), "0.97", "Patient_Responsibility")

        return ResponseEntity.unprocessableEntity().body(myCustomErrorBody).build();
    }
}


public class MyCustomErrorBody {

    private boolean status;
    private String errorMessage;
    private String version;
    private String coreName;

    // constructor and getters setters ommitted

}

关于spring boot错误处理的链接:

Official spring boot documentation

Baeldung exception-handling-for-rest-with-spring

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 2011-08-10
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多