AFQueryStringPairsFromKeyAndValue not giving proper URL with NSArray? - ios

I am trying to send following parameters in GET method call:
{
query = {
"$or" = (
{
name = yes;
},
{
status = Open;
}
);
};
}
But it seems it is not returning the proper URL:
baseURL/objects?query%5B%24or%5D%5B%5D%5Bname%5D=yes&query%5B%24or%5D%5B%5D%5Bstatus%5D=Open
I was expecting to "Or" my data, but it is doing "And".
I am using AFURLRequestSerialization class.
I have followed this SO, but it gives me all the object without applying any query.
AFNetworking GET parameters with JSON (NSDictionary) string contained in URL key parameter
It was working properly in POST call, but in GET it is not working as expected.

I have resolved this by converting dictionary against query key to a string and adding this string as a value of key query in the dictionary.
So my parameters will look like:
parameters: {
query = "{\"$or\":[{\"name\":\"yes\"},{\"status\":\"Open\"}]}";
}
Then I am passing this dictionary to AFNetworking.

Related

Use JSONAssert on part of JSON with RESTAssured

I am able to retrieve JSON from a service using RESTAssured.
I would like to use the JSONPath capability to extract JSON and then compare it using JSONAssert.
Here's my example:
#Test
public void doAPITestExample() throws JSONException {
// retrieve JSON from service
Response response = RestAssured.given().get("http://localhost:8081/mockservice");
response.then().assertThat().statusCode(200);
String body = response.getBody().asString();
System.out.println("Body:" + body);
/*
{"datetime": "2018-06-21 17:48:07.488384", "data": [{"foo": "bar"}, {"test": "this is test data"}]}
*/
// able to compare entire body with JSONAssert, strict=false
Object data = response.then().extract().path("data");
System.out.println("Response data:");
System.out.println(data.getClass()); // class java.util.ArrayList
System.out.println(data.toString());
// JSONAssert data with strict=false
String expectedJSON = "{\"data\":[{\"foo\": \"bar\"}, {\"test\": \"this is test data\"}]}";
JSONAssert.assertEquals(expectedJSON, response.getBody().asString(), false);
// How do I extract JSON with JSONPath, use JSONAssert together?
}
Approach 1 - using JSONPath to get JSONObject
How do I get JSONPath to return a JSONObject that can be used by JSONAssert?
In the code example:
Object data = response.then().extract().path("data");
This returns a java.util.ArrayList. How can this be used with JSONAssert to compare to expected JSON?
Approach 2 - parse extracted data with JSONParser
If I do data.toString(), this returns a string that cannot be parsed due to lack of quote handling for string values with spaces strings:
String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);
Result:
org.json.JSONException: Unterminated object at character 24 of [{foo=bar}, {test=this is test data}]
Approach 3 - Using JSON schema validation
Is is possible to extract just the data property from the JSON and run that against JSON Schema on just that part?
Note: the entire JSON that is returned is quite large. I just want to validate the data property from it.
What would an example of doing a JSON schema validation look for just the data property from the JSON?
Thanks;
You can use the method jsonPath in your response object.
Example:
// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo");
For more info about JSon path check here.

Extract a part of text value from response and store it in a variable by using junit/reassured?

I need to test an api endpoint where response of the endpoint will be like this
Response:
{
"items": [
{
"url": "http://www.localhost.com:8080/user?id=19909090"
}
]
}
I want to store the id value that is 19909090 to a variable. Can you please suggest some solution to achieve this ?
You can use JsonPath to read the value of url.
For example:
String url = from(json).get("$.items[0].url");
And then use java.net.URI to extract the query parameter value.
For example:
URI uri = URI.create(url);
String[] params = uri.getQuery().split("=");
// prints out 19909090
System.out.println(params[1]);

select in a parsed json, comparing id with an array of ids

i need to filter array result (get by parsed json).
if i know the exact id i can select in the json using
#my_art = ele_art.select { |articolo| articolo['id'] == 456 }
Now I have an array of ids called #myarray and i need to select in ele_art only the items with id in the array
Reading the array i have:
[279, 276]
i tried with
#my_art = ele_art.select { |articolo| articolo['id'] == #myarray }
or
#my_art = ele_art.select { |articolo| articolo['id'] in #myarray }
with no luck!
how can i solve?
#my_array is and array of ids, so, in that case you need to check if articolo['id'] is included in #myarray. For those cases, the Array class in Ruby has the include? method, which receives an object and returns true/false if the object is included or not in the array.
So, in your case try something like:
#my_art = ele_art.select { |articolo| #myarray.include?(articolo['id']) }

read JSON Key 0 in Swift

I have a HTTP GET request that returns either:
{"events":"Event Goes Here"}
or
{"service":"Service goes here"}
At the moment I'm writing two HTTP Get functions so that when I get to:
if let results: NSArray = jsonResult["services"] as? NSArray {
or
if let results: NSArray = jsonResult["events"] as? NSArray {
I know that Im getting the services or the events Json data.
I want to be able to streamline the HTTP Get request so that I can call in a single function:
func makeGETRequest(urlRequest: String) {
how do I read the string in json0 to be able to determine if its an event or a service?
You seem to already know how to parse the data, but are asking how you might wrap it up to avoid redundancy.
I think you are looking for something like this:
func getStuff(urlRequest:String) -> Result
where Result is an enum with associated values for your payload. Documentation can be found here
You could then call the function something like this:
switch (getStuff("someUrl")) {
case let .Events(events):
doStuffWith(events)
break
case let .Service(serviceStuff):
doStuffWith(serviceStuff)
break
}
The baseline for the form you suggest though, is that if you want to use a common function, you have to return a multiplexed type. Your other option, is for it to call type specific handler functions / closures for each of the possible types, so you are not relying on the return type, but are reacting to the results with further calls such that all processing is done by the time that your getStuff() function returns.
As far as actual parsing goes, you would just use a series of if-let unwrappings to check for which result you got.
I don't do Swift, so translate the following ObjC to Swift and it may work, this is just a snippet, but this won't work because json[#"XXX"] requires an NSDitionary
- (id)initWithJson:(NSArray *)json
{
NSArray* object = json[#"events"] ?: json[#"service"];
self = [super initWithJson:object];
if (self == nil)
{
return nil;
}
//do work
return self;
}
so, you should try to reform your JSON packet that you get from the server, I can't image it being set up in a way that it doesn't send you a dictionary first that you must then parse to an array.
or something like this:
NSString * valueYouWant = json[#"events"] ?: json[#"service"];
using this:
-(NSString*)getValue:(NSDictionary*)json
{
NSString * valueYouWant = json[#"events"] ?: json[#"service"];
return valueYouWant;
}
you would call this by doing sending your "response object" from the server to the NSString method above

rails how do I convert a variable into a symbol for use in a JSON string?

Trying to build a JSON string for use with a service and want to pass some of the JSON keys as variables.
I've tried:
def blah( field, value )
...
body = { request: { field.to_sym value } }
and
body = { request: { field.to_sym: value } }
but get errors in the console. What's the proper syntax here?
Thanks.
I'm guessing that you're looking for the hashrocket syntax:
body = { request: { field.to_sym => value } }
# -------------------------------^^
The JavaScript-style k: v notation can only be used with a limited set of literal symbols.

Resources