org.json JSONObject 在从 spring 启动控制器返回时向 JSONObject 添加额外的对象

org.json JSONObject adding extra object to JSONObject while returning it from spring boot controller

我正在从 spring 引导控制器 (1.5.16.RELEASE) 返回 org.json JSON 对象。我在其中得到了一个额外的地图对象。

我的代码-

@GetMapping(value = Constants.API_LOGIN)
    public Object login(@RequestParam String userName, @RequestParam String password) throws JSONException  {

        UserAuth userAuth = new UserAuth();
        UserAuth user = null;

        try {
            Preconditions.checkArgument(!Strings.isNullOrEmpty(userName), "empty UserName");
            Preconditions.checkArgument(!Strings.isNullOrEmpty(password), "empty password");

            userAuth.setUserName(userName);
            userAuth.setPassword(password);
            user = authService.checkAuth(userAuth);

        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }

        JSONObject json = new JSONObject();

        if (user != null) {
            json.put("status", true);
            json.put("message", "login success");
            return ResponseEntity.status(HttpStatus.OK).body(json);
        } else {
            json.put("status", false);
            json.put("message", "username or password doesnt match");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(json);
        }
    }

pom.xml

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

预计Json

 {
        "message": "login success",
        "status": true
 }

我得到 JSON

{
    "map": {
        "message": "login success",
        "status": true
    }
}

我不知道为什么我会在我的 JSON对象中得到额外的地图对象。

我认为问题在于默认的 Springboot JSON 序列化程序是 Jackson,它不知道如何处理 JSONObject 所以它将它包装到一个 Map<String, Object> 中键是 map,值是你的 JSONObject。 在你的情况下,只使用地图会简单得多:

@GetMapping(value = Constants.API_LOGIN)
public ResponseEntity<Object> login(@RequestParam String userName, @RequestParam String password) throws JSONException  {
    .....
    Map<String, Object> json = new HashMap<>();
    json.put("status", true);
    json.put("message", "login success");
    return ResponseEntity.status(HttpStatus.OK).body(json);
}

或者我想另一种解决方案是简单地 return 将字符串棒 json.toString 插入主体

@GetMapping(value = Constants.API_LOGIN)
public String login(@RequestParam String userName, @RequestParam String password) throws JSONException  {
    ....
    JSONObject json = new JSONObject();
    json.put("status", true);
    json.put("message", "login success");
    return ResponseEntity.status(HttpStatus.OK).body(json.toString());
}