如何将MultipartFile文件的内容转换为JSON字符串

huangapple 未分类评论57阅读模式
英文:

How to convert content of MultipartFile file into JSON string

问题

以下是翻译好的部分:

我有一个名为Person.Java的文件。

public class Person {
    private String firstName;
    private String lastName;
}

文件存储在位置:C:\Users\Person.Java;此文件不是项目的一部分。

我编写了一个REST API端点,它接受此文件作为输入并读取该文件。

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

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

        // 在这里应该写什么
    }
}

在读取后,我希望将此文件的内容转换为JSON格式。

{
    "firstName": "",
    "lastName": ""
}

因此,要求是将Java文件(一个类)作为输入传递给控制器,并生成相应的JSON字符串作为输出。

英文:

I have one file Person.Java

public class Person {
private String firstName;
private String lastName;
}

file is stored at location say : "C:\Users\Person.Java"; This file is not part of the project.

I have written REST API endpoint which is accepting this file as a input and reading this file.

@PostMapping(value = &quot;/poc/jsobj&quot;, produces = {APPLICATION_JSON_VALUE})
public ResponseEntity&lt;ResponseMessage&gt; convertToJson(@RequestParam(&quot;file&quot;) MultipartFile file) {

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

    //what should I write here
}}

After reading I want to convert content of this file into JSON format.

{
&quot;firstName&quot;:&quot; &quot;,
&quot;lastName&quot;:&quot; &quot;
}

so, the requirement is take java file (a class) as input to controller and generate corresponding json String as it's output.

huangapple
  • 本文由 发表于 2020年6月6日 00:44:54
  • 转载请务必保留本文链接:https://java.coder-hub.com/62220306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定