简体   繁体   中英

serialization of object to json in rest-assured request body

I'm making a rest api using resteasy , and testing it with rest-assured .

Let's say that I have a class, message , with a property text .

@XmlRootElement
public class message {
  @XmlElement
  public String text;
}

The following test will try to post this object to a given 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.

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?

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

// 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/");

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 Jackson or GSon to get a JSon format compatible with RestAssured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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