Fiddler HttpRequest Composer - json.stringify - asp.net

I want to use Fiddler to compose a HTTPRequest to an ASP.Net MVC Controller/Action. However, in this request, I want to be able to pass a JSON object as an object, and not simply as key value pairs which map to the different arguments in the method. I want to be able to test passing a complex type as one argument in the Controller/Action method.
This can be done in JQuery using Json.stringify({{json here}}) which passes the object as an object to MVC, and doesn't parse it into KVPs. Once again, I'm just looking to be able to test the same behavior in Fiddler, if it's possible.
Fiddler Request

The answer to this was simpler than I thought. What Json.stringify does, at it's core, is to wrap the Json string into an object which then becomes one single solitary KVP object, which then gets auto mapped based on the members and values of the Json Object passed and cast into your complex type object argument in your controller/action.
So, all I had to do was wrap the JSON object notation,
{
"FirstName": "Your",
"LastName": "Mom",
"Email": "yourmom#gmail.com",
"FilmAndSiteUpdates": true,
"CompanyUpdates": true
}
into a Json object "instance" so to speak by assigning it to a member by the same name of the method signature, like so...
{
"input": {
"FirstName": "Your",
"LastName": "Mom",
"Email": "yourmom#gmail.com",
"FilmAndSiteUpdates": true,
"CompanyUpdates": true
}
}
...and ASP.NET MVC does the implicit casting for you.

Related

Is it possible to create a JSON Schema that can validate a hashmap / dictionary as opposed to an object?

So if I have an object, let's call it a Person, like:
{
"email": "foo#bar.com",
"first"" "foo",
"last": "bar"
}
This Person object can all be validated quite well with JSON Schema. The issue is when multiple of these are arranged into a dictionary where the email field is used as the key and the object is the value. For example:
{
"foo#bar.com": {
"email": "foo#bar.com",
"first"" "foo",
"last": "bar"
},
"you#your.com": {
"email": "you#your.com",
"first": "Bob",
"last": "Bobton"
},
"me#mine.com": {
"email": "me#mine.com",
"first": "Deb",
"last": "Debbington"
}
}
This is a common way to structure data. Beyond the validation of the Person values, which can be handled well by a JSON Schema, there are a number of validations that would be useful on the dictionary:
The key is an email and can be validated as one.
The value is always a Person.
The key is always identical to the value's email field.
All the keys are unique.
Is it possible to implement these dictionary validations using JSON Schema?
The first two requirements, yes.
You can use patternProperties.
The other two you ask are not possible using JSON Schema. Sorry.
My expectation would be you receive the data in the first form from an API, validate, then map reduce to your desired structure.

Matching object in JSON with jsonpath in Spring Boot Test

I'm trying to write unit tests for a rest endpoint with Spring Boot Test that's going well but when I try to assert on an object in the json response with jsonPath an AssertionError is thrown even when contents are identical and the same.
Sample Json
{
"status": 200,
"data": [
{
"id": 1,
"placed_by": 1,
"weight": 0.1,
"weight_metric": "KG",
"sent_on": null,
"delivered_on": null,
"status": "PLACED",
"from": "1 string, string, string, string",
"to": "1 string, string, string, string",
"current_location": "1 string, string, string, string"
}
]
}
Code in Kotlin
mockMvc.perform(
get("/api/v1/stuff")
.contentType(MediaType.APPLICATION_JSON_UTF8)
).andExpect(status().isOk)
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("\$.status").value(HttpStatus.OK.value()))
.andExpect(jsonPath("\$.data.[0]").value(equalTo(stuffDTO.asJsonString())))
That throws AssertionError but the values are the same
Clicking on see difference says
How can I match an object in JSON with jsonPath? I need to be able to match an object because the object can contain many fields and it will be a PITA to match them individually
I came across what looks like the same issue, though it's hard to say without knowing what your asJsonString function is. Also I was using Java, not Kotlin. If it is the same issue:
It's due to jsonPath(expression) not returning a string, so matching it with one doesn't work. You need to convert stuffDTO into the correct type for matching using JsonPath ie. in a function such as:
private <T> T asParsedJson(Object obj) throws JsonProcessingException {
String json = new ObjectMapper().writeValueAsString(obj);
return JsonPath.read(json, "$");
}
Then .andExpect(jsonPath("\$.data.[0]").value(equalTo(asParsedJson(stuffDTO)))) should work.

How to Deserialize null response in js-data

The find method in js-data-http appears to have a special case where if item is falsey then it will reject the promise, otherwise it returns item. My problem is that some falsey values (0, null, '') are valid responses from my API.
For example if I ask for a relation that hasn't been set then the API responds with data null wrapped in a jsonapi envelope. This follows the jsonapi spec for fetching empty relationships:
{
"links": {
"self": "/articles/1/relationships/author",
"related": "/articles/1/author"
},
"data": null
}
I'm using the js-data-jsonapi library to help js-data and jsonapi get along. In that library the DeSerializer unwraps the jsonapi envelop. At that point js-data is back in charge and the unwrapped data null is the value for item in the find promise resolve method which causes js-data-http to reject the promise.
Right now I'm taking advantage of a special case in js-data-jsonapi to deserialize null data as an array because in JS Arrays are truthy. But then I must special case the detection for hasOne relations where now an empty array must be re-converted into null.
This seems like an overly complicated way of handling things, is there a better way that I am missing?
My setup uses:
"angular": "1.5.8",
"js-data": "2.9.0",
"js-data-angular": "3.2.1",
"js-data-jsonapi": "0.0.0-alpha.21",

Filter by type in Google AutocompleteService

I want to filter away establishments in my autocomplete service.
I have tried
var service = new google.maps.places.AutocompleteService;
var request = {
"input": "Nørregade",
"componentRestrictions": { "country": "dk" },
"types": ["(cities)", "(regions)", "geocode"]
};
service.getPlacePredictions(request, function(predictions, status) {
console.log(status) # => INVALID_REQUEST
});
(http://jsfiddle.net/gdk0j9eg/1/)
Following this link (https://developers.google.com/maps/documentation/javascript/reference#AutocompletionRequest) it seems that the autocomplete service does indeed take these types.
What am I doing wrong here?
See the documentation, you are only allowed to use a single type or type collection:
You may restrict results from a Place Autocomplete request to be of a certain type by passing a types parameter. The parameter specifies a type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types.

Why doesn't jquery turn my array into a json string before sending to asp.net web method?

So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:
$.ajax({
type: 'POST',
url: 'personalization.aspx/SetPersonalization',
data: "{'backerEntries':" + backerEntries + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: postcardManager.SetPersonalizationComplete
});
The post:
{'backerEntries':[object Object],[object Object],[object Object]}
The error response:
Invalid JSON primitive: object.
For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?
data: "{'backerEntries':" + backerEntries + "}",
..is the same as
data: "{'backerEntries':" + backerEntries.toString() + "}",
...which is pretty much useless. Use Duncan's suggestion if you just want to pass an encoded list of values with the name "backerEntries" in your querystring. If you want to JSON-encode the data, then get a JSON library and call JSON.stringify().
The data you are passing you are trying to pass it as a string already. If you want jQuery to transform it leave the whole thing as an object, e.g.
data:{backerEntries: backerEntries }
Assuming of course backerEntries is an array. jQuery should transform this and will append it to the querystring as that is its default behaviour. Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.
Since you're using ASP.NET, you can use the built-in ASP.NET AJAX serialization library:
var backerEntriesJson = Sys.Serialization.JavaScriptSerializer.serialize(backerEntries);
then pass that directly in your jQuery ajax call:
...
data: backerEntriesJson,
...
This is NOT valid JSON: { 'foo': 'bar' }
Isn't, wasn't ever, never will be. JSON processors are often very forgiving, which of course is a false convenience.
Read the specification. A string is defined to be enclosed in double quotes, not single quotes, not smiley face characters, not pieces of metal bent at right angles, not bricks. There's no mention of single quotes, period.
Now, property names are JSON strings. By definition, they MUST are enclosed in double quotes.
Valid: { "foo": "bar" }
valid" { "foo": 100 }
valid: { "foo": true }
valid: { "foo": [ "one", "two" ], "bar": false }
see www.json.org
see www.jsonlint.com

Resources