简体   繁体   English

Java Restful Web服务-一起发送响应和ID

[英]Java restful webservices - sending response and Id together

On user calling my webservice, I am inserting record in database and it generates auto-increment key. 当用户调用我的Web服务时,我正在数据库中插入记录,并且它会生成自动增量密钥。 I want to send response in following format : 我想以以下格式发送响应:

    {
    "status" : "success",
    "autogenerated_id" : 1

    }

Following is my code and o/p 以下是我的代码和o / p

WsResponse resp = new WsResponse();
resp.setStatus("success");
resp.addData("autogenerated_id", autogenerated_id);

Response is : 响应是:

 {
        "status": "success",
        "response": {
            "autogenerated_id": 8
        }
    }

What can I change so that I get autogenerated_id at same level as that of status ? 我可以更改什么,以便获得与status相同级别的autogenic_id? Or can I change the text "response" to anyother text like "data" ? 还是可以将文本“响应”更改为其他任何文本,例如“数据”?

You cannot do what you want and is has a simple reason. 您无法做自己想做的事情,并且有一个简单的原因。 The object you are seeing is the response object related to the HTTP connection (200->OK, 404->Not Found, 500-> Internal Server Error, etc), not the result status coming from the database procedure. 您看到的对象是与HTTP连接相关的响应对象(200-> OK,404->未找到,500->内部服务器错误等),而不是来自数据库过程的结果状态。 In addition to this, you can send back whatever you like, however it must be inside the response object. 除此之外,您还可以发送任何您喜欢的内容,但是它必须在响应对象中。 It Should look like this 它应该看起来像这样

{
        "status": "success", //result of the connection.
        "response": {
            "status": "success", //result of the db procedure.
            "autogenerated_id": 8
        }
    }

The returned object is converted to a string using different formats and encoding and then it is send back to the client (json in your case). 返回的对象使用不同的格式和编码转换为字符串,然后将其发送回客户端(在您的情况下为json)。 The client is who turns the string back to an object. 客户是将字符串转换回对象的人。 If your are printing the response object, then you can't change it. 如果要打印响应对象,则不能更改它。 However, if you are printing the data received from the server, then you can simply return a different object according to your needs. 但是,如果要打印从服务器接收的数据,则可以根据需要简单地返回另一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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