繁体   English   中英

Json 字符串作为外部 .java 文件对应的输出

[英]Json string as a output corresponding to the external .java file

我有一个具有以下字段的外部 .java 文件,

public class PersonDetails {
    private String firstName;
    private String lastName;
    private Integer hobby;  
    private List<String> address;
    private Map<String, BigDecimal> salary;
    private String[] position; 
}

我将此文件作为输入传递给 REST api 并尝试将其内容转换为 json 字符串

 @PostMapping(value = "/poc/jsobj", produces = {APPLICATION_JSON_VALUE})
    public ResponseEntity<ResponseMessage> convertToJson(@RequestParam("file") MultipartFile file) {

        JSONObject javaObjectDetials = new JSONObject();

        try {
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                String completeData = new String(bytes);
                System.out.print(completeData);

                String pattern = "(\\w*);";
                Matcher m = Pattern.compile(pattern).matcher(completeData);

                while (m.find()) {
                    System.out.println(m.group(1));
                    javaObjectDetials.put(m.group(1), "");
                }
            }
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(javaObjectDetials.toString()));
        } catch (Exception e) {
            String str = "";
            str = "Could not get the file: " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(str));
        }
    }

当我运行应用程序时,我得到如下的 json 字符串

{
    "jsonString": "{\"firstName\":\"\",\"lastName\":\"\",\"address\":\"\",\"position\":\"\",\"salary\":\"\",\"hobby\":\"\"}"
}

但根据每个字段的数据类型,我想要如下的 json 字符串,

{
    "firstName":"",
    "lastName":"",
    "address":[],
    "position":[],   
    "salary": {},
    "hobby": 1
}

谁可以帮我这个事?

有更简单的方法来创建表示您是对象数据的 JSON 字符串。 看看杰克逊或gson。 这些库将自动执行您现在正在执行的操作。

看起来您正在使用 Spring 创建 REST API。 所以它变得更加容易。 Spring 还使用 Jackson 创建响应实体的 JSON 或 XML 表示。 (在本例中为 ResponseMessage)所以理论上您可以执行以下操作:

@PostMapping(value = "/poc/jsobj", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<PersonDetails> convertToJson(@RequestParam("file") MultipartFile file) {
    try {
        if (!file.isEmpty()) {
            ObjectMapper mapper = new ObjectMapper();
            PersonDetails personDetails = mapper.readValue(file.getBytes(), PersonDetails.class)
            return ResponseEntity.status(HttpStatus.OK).body(personDetails);
        }
    } catch (Exception e) { // Please never ever catch all exceptions. I think in this case you want to catch an IOException?
        String error = "Could not get the file: " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED);
    }
}

现在,对*/poc/jsobj的请求包含带有 JSON 对象的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM