java 在放心的请求正文中将对象序列化为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10709409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
serialization of object to json in rest-assured request body
提问by Vegar
I'm making a rest api using resteasy, and testing it with rest-assured.
我正在使用resteasy制作一个 rest api ,并使用rest-assured进行测试。
Let's say that I have a class, message
, with a property text
.
假设我有一个message
具有属性的类text
。
@XmlRootElement
public class message {
@XmlElement
public String text;
}
The following test will try to post this object to a given url:
以下测试将尝试将此对象发布到给定的 url:
message msg = new message();
msg.text = "some message";
expect()
.statusCode(200)
.given()
.contentType("application/json")
.body(msg)
.when()
.post("/message");
The msg object is serialized to json and posted, but not in the way that I want - not in the way resteasy need, that is.
msg 对象被序列化为 json 并发布,但不是以我想要的方式 - 不是以 resteasy 需要的方式。
What's posted:
发布的内容:
{ "text": "some message" }
What's working:
什么工作:
{ "message": { "text": "some message" } }
Does anyone have any clue on how I can make this work as expected?
有没有人知道我如何按预期进行这项工作?
回答by Jonathan Morales Vélez
I know there's already an answer for this but i want to share the way i was able to send a json object. Someone may find it helpful
我知道已经有一个答案,但我想分享我能够发送 json 对象的方式。有人可能会发现它有帮助
// import org.json.simple.JSONObject;
JSONObject person = new JSONObject();
person.put("firstname", "Jonathan");
person.put("lastname", "Morales");
JSONObject address = new JSONObject();
address.put("City", "Bogotá");
address.put("Street", "Some street");
person.put("address", address);
String jsonString = person.toJSONString();
// {"address":{"Street":"Some street","City":"Bogotá"},"lastname":"Morales","firstname":"Jonathan"}
// import static com.jayway.restassured.RestAssured.*;
given().contentType("application/json")
.body(jsonString)
.expect().statusCode(200)
.when().post("http://your-rest-service/");
回答by thostr
You are probably using the built in Jettison JSON serializer with RestEasy. Jettison uses the XML-> Json convention (also known as BadgerFish). Replace Jettison with Hymanson or GSon to get a JSon format compatible with RestAssured.
您可能正在使用带有 RestEasy 的内置 Jettison JSON 序列化程序。Jettison 使用 XML-> Json 约定(也称为 BadgerFish)。用 Hymanson 或 GSon 替换 Jettison 以获得与 RestAssured 兼容的 JSon 格式。