serialization of object to json in rest-assured request body

15,505

Solution 1

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.

Solution 2

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/");
Share:
15,505
Vegar
Author by

Vegar

SOreadytohelp

Updated on June 27, 2022

Comments

  • Vegar
    Vegar almost 2 years

    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?

  • vikramvi
    vikramvi over 7 years
    Still have few doubts , I created Java hashmap and it failed. But your solution worked , any idea why it might have failed with hashamp approach . I have nested json as per your example.
  • Jonathan Morales Vélez
    Jonathan Morales Vélez over 7 years
    Hey vikramvi, I did this long time ago and I can't really tell what happens when using a hashmap.