Rest-Assured using Jayways Jsonpath? - json

I have spent a long time figuring out some JsonPath using Jayways version, my query is the following:
$.items[?(#.To[0].Mailbox == 'foobar')]..Body
However, this does not work with Rest-Assured, when executing, I am shown the following error:
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 34.
$.items[?(#.To[0].Mailbox == 'foobar')]..Body
Do I need to rewrite this expression in GPath format? if so, what would that look like? or can I somehow have Rest-Assured use this preferred JsonPath expression?
here is a small [WIP] piece of code as of now, just trying to get the expression working, then I will fix up the method correctly:
public String readInbox(String emailAddress) {
Response response = given().log().all().when().get(MESSAGES_ENDPOINT);
JsonPath jsonPath = new JsonPath(response.asString());
String emailAddress = jsonPath.getString("$.items[?(#.To[0].Mailbox == 'foobar')]..Body");
System.out.println(accountVerificationEmailHyperlinkByEmailAddress);
return "";
}

resolved this by just excluding rest assured completely and using jsonPath on the response body like so:
emailBodies = JsonPath.read(given().when().get(MESSAGES_ENDPOINT).getBody().asString(), generatePayLoadForEmailPrefixOf(emailPrefix));

Related

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#

I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";

How to extract the Substring from URL present in JSON response using JMeter

I've the below JSON response received from the HTTP request. I want to extract the parameters from the node "url" present in the JSON response.
{"Id":"7S9LyBqyv1e0trKrVuP1OOZGHeg","Url":"https://abcd.com:443/u/custom-response?prov=34545sdf-9013e2e61e66&realmeId=%2Fxxxx","realmeId":"/abcd"}
In the above JSON response, i want to retrieve the value of "prov" which is 34545sdf-9013e2e61e66 using JMeter.
Solution Tried: Used Beanshell to read the response.
String url = vars.get("successURL");
vars.put("responseURL",url.toString());
responseURL = responseURL.replaceAll(":"," ");
log.info("String URL "+responseURL.toString());
Error Message:
attempt to resolve method: toString() on undefined variable or class name: responseURL
I think you need to update this line:
responseURL = responseURL.replaceAll(":"," ");
to something like:
responseURL = vars.get("responseURL").replaceAll(":"," ");
However I don't guarantee that it will work because I don't know how do you get this successURL variable.
What will work is doing everything in one shot using JSR223 PostProcessor and Groovy language which has built-in JSON support, suggested code:
def url = new groovy.json.JsonSlurper().parse(prev.getResponseData()).Url
def params = org.apache.http.client.utils.URLEncodedUtils.parse(new URI(url), 'UTF-8')
params.each { param ->
log.info(param.getName() + '=' + param.getValue())
}
Demo:
More information: Apache Groovy - Why and How You Should Use It
You don't need to use complex Beanshell coding, You can do this easily using - Regular Expression Extractor.
Here the example:-
You can see required value extracted and stored in variable name give in Regular expression extractor:
To understand try out reg-ex, you can use https://regex101.com/

groovy "MissingMethodException" RESTAPI call

I am trying to access data from RESTAPI using groovy code where i am getting error as below:
groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: () values: []
Possible solutions: wait(), chars(), any(), wait(long), take(int), tap(groovy.lang.Closure)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:70)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:182)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeClosure(ScriptBytecodeAdapter.java:586)
The error is coming mostly on the below part of the lines from code :
String requestString = getRequestStringPrefix() + sb.toString()
readHistory(authToken,ricMap,outFile)
writeInstFile(outFile)
I am really new in the groovy coding and not understanding exactly the cause of the issue and how to resolve this issue in the code.
With this getRequestStringPrefix() you are calling a method with that name or as a shortcut a method call() on the underlying object, then it looks like getRequestStringPrefix.call().
I'm not sure what your intention was, but the line:
String requestString = getRequestStringPrefix() + sb.toString()
should look like
String requestString = getRequestStringPrefix + sb.toString()
because the variable getRequestStringPrefix (a strange name for a var) is defined as String further down:
String getRequestStringPrefix = """{
"ExtractionRequest": {..."""

Parse JSON from a string that contains more than JSON

A third party NuGet package throws an exception and in its exception message there is a an error and a JSON object:
Request failed, Message: {"Message":"Some error message"}
How can I extract the JSON from string and get the Message property?
I know that I could use Regex to format the string before passing it to deserializer or even trim the text until the first {
Is there a cleaner way to do it using Json.NET?
No.
Json.Net is built to parse JSON. If you have extra text in the string that is not JSON, the parser will not be able to make sense of it. Your best bet is to strip off the text before the first brace (and after the last brace), like you suggested in your question. You can make a helper method to do this easily:
public static string ExtractJson(string text)
{
int i = text.IndexOf('{');
int j = text.LastIndexOf('}');
return i > -1 && j > i ? text.Substring(i, j - i + 1) : null;
}
Once you've extracted the JSON, you can use Json.Net like you normally would.
Fiddle: https://dotnetfiddle.net/WoflVv

JSON accepted format according to Newtonsoft Json

I am trying to parse some JSON objects which is made just of (string,string) pairs, in order to emulate Resjson behaviour. The file I am parsing contains this.
{
"greeting":"Hello world",
"_greeting.comment":"Hello comment.",
"_greeting.source":"Original Hello",
}
Please note the last comma is incorrect, and I also used http://jsonlint.com/ to test JSON syntax. It tells me it is incorrect, as I expected. My - slightly modified - code is :
string path = #"d:\resjson\example.resjson";
string jsonText = File.ReadAllText(path);
IDictionary<string, string> dict;
try
{
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonText);
}
catch(Exception ex)
{
// code never reaches here
}
My above code returns the IDictionary with the 3 keys as if the formatting was correct. If I serialize back, the string obtained is without the last comma.
My questions are :
Is Newtonsoft.Json so permissive that it allows users slight errors ?
If so, can I set the permissiveness so that it is more strict ?
Is there a way to check if a string is valid JSON format, using
Newtonsoft.Json with and/or without the permissiveness?