0

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?

JavaFan
  • 23
  • 5

1 Answers1

0

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.

magicmn
  • 1,787
  • 7
  • 15
  • Thanks for this, but here class PersonDetails is not a part of the project... its external .java file...then how can i use it here PersonDetails personDetails = mapper.readValue(file.getBytes(), PersonDetails.class) ???? – JavaFan Oct 01 '20 at 18:47
  • Put it in the project. Or create the same class again. Working with classes makes life much easier – magicmn Oct 01 '20 at 19:03
  • Input file may vary.. sometimes it is PersonDetails.java, sometime it is employee,java or anything with .java extension.. I want to convert any input .java file into corresponding json string... – JavaFan Oct 01 '20 at 19:22
  • Could you provide some information on the content of the multi part file? How is he data formatted in there? – magicmn Oct 01 '20 at 21:23
  • multipart file is nothing but .java file. In above example it contains public class PersonDetails { private String firstName; private String lastName; private Integer hobby; private List address; private Map salary; private String[] position; } – JavaFan Oct 01 '20 at 22:11
  • So you want to create a empty JSON structure which is equal to the structure of the Java file? Doing it manually is still a ton of work, but the only other thing I can think of is the following: Compile the uploaded files at runtime and load them into you're current program. (https://stackoverflow.com/a/21544850/9712270) Then you can use some reflection to get the class and create an empty instance of it. It's pretty hacky and is potentially a huge security risk. – magicmn Oct 02 '20 at 13:13