JSONObject always returns “empty”: false

2019-08-26 20:58发布

There is a Spring Rest Controller :

@RestController
@RequestMapping("secanalytique")
public class SectionAnalytiqueController {

    @GetMapping(value = "/sectionbyaxepro/{codecomp}", produces = "application/json")
    public JSONObject getByAxePro(@PathVariable String codecomp) {
        JSONObject jsonModel = new JSONObject();
        jsonModel.put("cce0","frityyy");
        return jsonModel;
    }

}

I made a test with Postman : http://172.20.40.4:8080/Oxalys_WS/secanalytique/sectionbyaxepro/8 ; and what I got is always

{
    "empty": false
}

So what is wrong ?

2条回答
Ridiculous、
2楼-- · 2019-08-26 21:52

There was one issue with your implementation that you are creating json object explicitly and returning it which is not required.
Instead, you should just send your java POJO/class, spring will convert it to JSON and return it.
Spring uses Jackson as the default serializer/deserializer. Here since an object is already JSONObject, Jackson does not know how to serialize it.
There are two way to solve this
1. Define your own data type and populate it.

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

@GetMapping(value = "/sectionbyaxepro/{codecomp}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> getByAxePro(@PathVariable String codecomp) {
    Map<String, String> map = new HashMap<>();
    map.put("cce0","frityyy");
    return ResponseEntity.status(HttpStatus.OK).body(map);
}
  1. Modify your existing code to either of the following ways.

1

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

@GetMapping(value = "/sectionbyaxepro/{codecomp}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getByAxePro(@PathVariable String codecomp) {
    JSONObject jsonModel = new JSONObject();
    jsonModel.put("cce0","frityyy");
    return ResponseEntity.status(HttpStatus.OK).body(jsonModel.toString());
}

2

@GetMapping(value = "/sectionbyaxepro/{codecomp}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getByAxePro(@PathVariable String codecomp) {
JSONObject jsonModel = new JSONObject();
jsonModel.put("cce0","frityyy");
return jsonModel.toString();
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-26 21:52

Instead of creating JSONObject manually you can handle it in this way

@GetMapping(value = "/sectionbyaxepro/{codecomp}")
    public ResponseEntity<?> getByAxePro(@PathVariable("codecomp") String codecomp){
        Map map = new HashMap<>();
        map.put("key", "value");
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
查看更多
登录 后发表回答