简体   繁体   中英

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

I have one external .java file which is having below fields,

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

I am passing this file as a input to the REST api and trying to converts its contents into json string

 @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));
        }
    }

When I run the application, i am getting json string as below

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

but depending on the datatype of each field i want json string as below,

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

Can anyone help me on this?

There are much easier ways to create JSON strings that represents you're object data. Have a look at Jackson or gson. These libraries will automatically do what you are doing right now.

It looks like you are using Spring to create a REST API. So it gets even easier. Spring also uses Jackson to create a JSON or XML representation of you're response entity. (In this case the ResponseMessage) So in theory you can just do the following:

@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);
    }
}

Now a request to */poc/jsobj contains a response with the JSON object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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