Fetching Value From Json Object Stored as String for a Key in Response payload - rest-assured

How do I read a value from below response payload. From the second property in this JSON object, how do I fetch the value for the 'status' i.e "Active" or any other value for response key.
{
"signature": "1hdj12493039282849922",
"response": "{'UsersList':[{'userName':'Madan Jones','mobileNumber':'767780987','status':'Active','statusCode':null}],'status':0,'messageCode':null,'message':null,'errorMap':null}"
}
Any help is greatly appreciated!! Thanks in advance!!

Your response contains just a text that only looks like another json. So in order to do a check you have to fetch that value, parse it and hope that it would be a valid json too.
public static void main(String[] args) throws JsonProcessingException {
String str = RestAssured
.get("http://demo1954881.mockable.io/textjson")
.jsonPath().get("response");
JsonPath jsonPath = new JsonPath(str.replace("'", "\""));
String status = jsonPath.get("UsersList.find{u -> u.userName = 'Madan Jones'}.status");
MatcherAssert.assertThat(status, Matchers.equalTo("Active2"));
}
In your particular example JsonPath does not like that your field names are wrapped with ' so I change them to be proper double-quotes.

Related

API returning text/html rather than JSON when triggered using RestArrured

I'm triggering the Zomato api for the collections request, however, I keep getting the headers as if they were text/html. Postman returns them as JSON, which is what I need. All other Zomato apis I've tested so far are returning JSON but collections and not sure why. That's what I have on my attempts to force the JSON as the type for the response.
#Test
public void testGetCousinesApiReturnsItemsInAscendingAlphabeticalOrder() {
Map<String, Object> map = new HashMap<>();
map.put("city_id", 61);
Response r = given()
.baseUri(baseUrl)
.basePath("/cousines")
.queryParams(map)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.contentType("application/json\r\n")
.header("Accept", "application/json").and()
.header("Content-Type", "application/json")
.header("user-key", zomatoKey)
.log().body(false)
.get();
System.out.println(r.getContentType());
}
I convert response to JsonPath :
public static JsonPath getJsonPath (Response res) {
String json = res.asString();
System.out.println("returned json: " + json);
return new JsonPath(json);
}
and then use this JsonPath to get each value of Response:
JsonPath jp = getJsonPath(res);
String type = jp.get("type");

Map one field value to other field using Gson on condition like if first one is null or having value zero

I am trying to map one field value to other if that is null or zero. I am using Gson library to parse Json. Is there any way to map values on condition base. I tried using JsonAdapter where I can put condition for that field but unable to find out solution how to get other field value there to put in that.
Write your own deserializer implementing JsonDeserializer<Element> something like below according json response-
class CustomDeserializer implements JsonDeserializer<Element> {
#Override
public Element deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
JsonObject jobject = json.getAsJsonObject();
JsonObject object = jobject.get("key").getAsJsonObject();
if(object == null){
}
return null;
}
}
Usage -
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Element.class, new CustomDeserializer());
Gson gson = gsonBuilder.create();

Grab a single value from json response

First check two screen shots. One is debug error one is for json data visual view to give you better understanding. My main goal is to grab only "campaignId" value form this json response. I already tried to use JObject parse but getting error because RestSharp output not json string format so. Now tell me how can i grab that "campaignId" value of json response. Thanks in advance.
static void addEmailToList(string ListName, string Email, string Name)
{
var client = new RestClient("https://api.getresponse.com/v3/campaigns?query[name]="+ListName);
var GetIdreq = new RestRequest(Method.GET);
GetIdreq.AddHeader("X-Auth-Token", "api-key 948df-my-key-7f3c6");
GetIdreq.AddParameter("application/json", ParameterType.RequestBody);
var GetIdres = client.Execute(GetIdreq);
dynamic data = JObject.Parse(GetIdres);
}
You should assign the value of Content of response to your local variable. You can try this.
var GetIdres = client.Execute(GetIdreq).Content;
dynamic data = JObject.Parse(GetIdres);

Posting multipart form data to seam+RESTeasy fails marshalling to InputStream

I'm trying to post image data to a seam+RESTeasy endpoint and I'm getting a very cryptic error during JBoss startup. The HTTP request I'm sending has a content-type of multipart/form-data which has a single image/jpeg part with name "attachment". My service method looks like this:
#POST
#Path("uploadSymptomsImage/{appointmentGUID}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public String uploadSymptomsImage( #FormParam("attachment") InputStream fileInputStream,
#PathParam("appointmentGUID") String strAppointmentGUID )
{ ...
The error that I get is during startup:
Caused by: java.lang.RuntimeException: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.FormParam("attachment") on public java.lang.String com....AppointmentRestService.uploadSymptomsImage(java.io.InputStream,java.lang.String) for basetype: java.io.InputStream
at org.jboss.resteasy.core.StringParameterInjector.initialize(StringParameterInjector.java:206) [:]
at org.jboss.resteasy.core.StringParameterInjector.<init>(StringParameterInjector.java:57) [:]
at org.jboss.resteasy.core.FormParamInjector.<init>(FormParamInjector.java:22) [:]
My understanding was that media types could be automatically marshalled to InputStream. I've also tried java.io.File, java.io.Reader - both with same error. When I replace with byte[] or String I get a zero length array, or null as the parameter value.
How would you go about debugging this? Also, is it possible to access the raw request or pre-marshalled values?
Any suggestions here would be greatly appreciated.
You should retrieve the contents using MultipartFormDataInput. See the following example:
#POST
#Path("uploadSymptomsImage/{appointmentGUID}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public String uploadSymptomsImage(#PathParam("appointmentGUID") String strAppointmentGUID,
MultipartFormDataInput formData) {
Map<String, List<InputPart>> formDataMap = formData.getFormDataMap();
List<InputPart> attachments = formDataMap.get("attachment");
for(InputPart attachment : attachments) {
String fileName = extractFilename(attachment);
if(fileName.isEmpty()) continue;
InputStream in = attachment.getBody(new GenericType<InputStream>() {});
// Interact with stream
}
// Respond
}
The extractFilename method is a helper method I wrote:
private static String extractFilename(final InputPart attachment) {
Preconditions.checkNotNull(attachment);
MultivaluedMap<String, String> headers = attachment.getHeaders();
String contentDispositionHeader = headers.getFirst("Content-Disposition");
Preconditions.checkNotNull(contentDispositionHeader);
for(String headerPart : contentDispositionHeader.split(";(\\s)+")) {
String[] split = headerPart.split("=");
if(split.length == 2 && split[0].equalsIgnoreCase("filename")) {
return split[1].replace("\"", "");
}
}
return null;
}

ASP.Net MVC: how to create a JsonResult based on raw Json Data

Having a string containing the following raw Json data (simplified for the sake of the question):
var MyString = "{ 'val': 'apple' }";
How can I create a JsonResult object representing MyString?
I tried to use the Json(object) method. but it handles the raw json data as an string -logically :P-. So the returned HTTP response looks like:
"{ 'val': 'apple' }"
instead of the given raw Json Data:
{ 'val': 'apple' }
this is what I want to achieve:
The Json() method on Controller is actually a helper method that creates a new JsonResult. If we look at the source code for this class*, we can see that it's not really doing that much -- just setting the content type to application/json, serializing your data object using a JavaScriptSerializer, and writing it the resulting string.. You can duplicate this behavior (minus the serialization, since you've already done that) by returning a ContentResult from your controller instead.
public ActionResult JsonData(int id) {
var jsonStringFromSomewhere = "{ 'val': 'apple' }";
// Content() creates a ContentResult just as Json() creates a JsonResult
return Content(jsonStringFromSomewhere, "application/json");
}
* Starting in MVC2, JsonResult also throws an exception if the user is making an HTTP GET request (as opposed to say a POST). Allowing users to retrieve JSON using an HTTP GET has security implications which you should be aware of before you permit this in your own app.
The way I have generated json data from a string is by using JavaScriptResult in the controller:
public JavaScriptResult jsonList( string jsonString)
{
jsonString = "var jsonobject = new Array(" + jsonString + ");";
return JavaScript(jsonString)
}
Then when you request pass the json string to that action in your controller, the result will be a file with javascript headers.
I think you can use the JavaScriptSerializer class for this
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = js.Deserialize("{ 'val': 'apple' }", typeof(object));

Resources