Configure webAPI oData name for odata.count - json

Anyone know how to customize the names asp.net webapi returns? I'm really interested in changing "odata.count" to be something like "odata-count" - the dot is messing up Infragistics IgniteUI controls.
Example URL: http://localhost/odata/users?$inlineCount=allpages&$top=10
Example oData:
{
"odata.metadata":"http://mydomain/odata/$metadata#Users",
"odata.count":"3",
"value":[
{"FirstName":"Alan","MiddleName":"A.","LastName":"Arlington"},
{"FirstName":"Brad","MiddleName":"B.","LastName":"Boston"},
{"FirstName":"Dirk","MiddleName":"J.","LastName":"Watkins"}
]
}
I could also live with putting all oData metadata in a separate top-level object like:
{
"odata":{
"metadata":"http://mydomain/odata/$metadata#Users",
"count":"3",
},
"value":[
{"FirstName":"Alan","MiddleName":"A.","LastName":"Arlington"},
{"FirstName":"Brad","MiddleName":"B.","LastName":"Boston"},
{"FirstName":"Dirk","MiddleName":"J.","LastName":"Watkins"}
]
}

OData protocol defines a standard representation for OData requests and responses in JSON format. The metadata key names like odata.count are defined by the spec and are not configurable to improv inter-operability with standard clients.
In short, you cannot customize those names.

Related

OData Custom Action Response Restrictions

We have to talk to a Microsoft Dynamics 365 Api. When calling an custom action we retrieve a json as in the example below
{
"#odata.context": "just-a-domain",
"ids": "[{\"account\":\"whatever_id\",\"name\":\"test 2\"}]"
}
As you see the value of ids comes as string, but it should be json. Is there any restrictions for the return values in Dynamics 365?
The expected output should be like
{
"#odata.context": "just-a-domain",
"ids": [
{
"account": "whatever_id",
"name": "test 2"
}
]
}
Didn't find anything about it in the documentation. But the guy who's implementing the custom actions claims it is not possible to do it in any other way.
These are the data types supported in Custom action output parameter:
That being said, JSON is not the straight supported Output param type, but you can ask your CRM developer to give you back some fixed format anyway.
Simply serialized JSON in String Output type, EntityCollection Or Entity types may help you if I understand your need correctly. Read more

Is there a json validation framework in play based on a specified grammar

An automated system is going to feed the application[Play with Scala] with JSON's and the contract of the integration is that there would be no validation required on JSON's since it will be always deemed right. But for testing purposes when we seed the data more often than not we are not able to send the correct JSONs. We would like to validate the JSON's we receive based on a set of grammars. Is there a library that already does this. Or is there a better way to do this?
Example: Grammar for valid Json :
"header"->[String, mandatory],
"footer"->[String],
"someArray"->Array[String, mandatory],
"someArrayObject"->Array[
{
{"key1"->Int, mandatory},
{"key2"->String}
},
mandatory
]
and passing,
{
"header":"headerContent",
"footer":"footerContent",
"someArray":["str1", "str2"],
"someArrayObject"->[
{"key1":4, "key2":"someStringValue"},
{"key1":5, "key2":"someOtherStringValue"}
]
} // would pass
{
"header":"headerContent",
"footer":"footerContent",
"someArray":["str1", "str2"]
} // would notpass since someArrayObject though declared mandatory is not provided in the sample json
I think play-json will satisfy you play-json
In play-json you don't create a validator as it is, but a json transformer which is a validator in itself. The author of the framework wrote a series of blog-posts to show how to work with it: json-transformers
* Haven't noticed you use play) Play has play-json included by default.
You don't have to roll out your own DSLs. This is why we have schemas. Just like using XML schemas to validate your XML docs, you can define a JSON schema to validate your JSON objects. I had a similar requirement when building a RESTful web service using Play. I solved it by using the JSON Schema Validator library.
I have used the JSON Schema draft v3. The library supports draft v3 and draft v4. You can validate your schemas against possible JSON inputs using a web application that uses the same library. The web app is hosted here.
Also there are pretty nice examples that use the draft v4. You can check them out from here.
In Play 2, I have composed an action that takes the schema resource file name as input. This keeps away a lot of JSON validation code from the controller action itself.
#JsonValidate("user-register.json")
public static Result create() {
...
}
This way, all JSON Validation code stays in one place. Pretty neat :)

Wrapping a Web API response in JSON but still having it work with IQueryable and oData

I have an ASP.NET Web API project, and I want to use oData filters in the project, with the ASP.NET oData preview package. This means I need to use IQueryable as the response type.
Unfortunately, the consumer requires the response wrapped like so:
{
"total": 2,
"success": true,
"data": [
{ object1 },
{ object2 } ]
}
I created a wrapper object which assigns the IQueryable response from my original version to the "data" property, and sets the values for the "total" and "success" properties as well. This creates the JSON response the consumer is looking for. But it's no longer IQueryable, which means I can't implement oData filters.
I was hoping to take my wrapper object and make it implement IQueryable by setting its enumerators, etc. However, I don't think this will work because I have to assign the Provider and Expression properties to implement the interface, and I don't know what I should put there. I'm using a Repository pattern with IoC, and the EntityFramework Code First data access is in a separate project, with concrete objects assigned to the interface placeholders using Ninject. Perhaps I can abstract out the interfaces all the way from the data access layer so that the the Repository objects carry a reference to an IQueryProvider. Do you think this would work, and allow it to support the automated oData integration?
Here's how you do it. Behind the scenes, [Queryable] just creates an instance of ODataQueryOptions and then applies it to the queryable you return. The good news is that you can parameter bind ODataQueryOptions and have code that looks like this:
public Wrapper<MyObject> Get(ODataQueryOptions<MyObject> queryOptions)
{
IQueryable<MyObject> queryResults = queryOptions.ApplyTo(dbSet);
return Wrap(queryResults);
}
You don't even need [Queryable] anymore because you're doing what it would have done for you. Hope that helps.

WCF Data Service - JSON response has extra "results" section

Using the WCF Data Services Toolkit, or the other ways to support the $format param such as JSONPSupportInspectorAttribute I am getting some json responses that are a little odd to me.
Why does my json look like:
{
"d" : {
"results": [
{
"__metadata": {
When the json from OData.org $format is as follows:
{
"d" : [
{
"__metadata": {
Why does mine have an extra "results" sub section?
My data service is just built directly onto my entity framework model. Do I have to use a specific context template for this to go away?
This is versioning. In V2 we added the server driven paging and inline count features which need to store additional metadata on the feed. But since the feed in V1 was just a JSON array, there was no place to put such metadata.
So in V2 all feeds in responses are wrapped in "results" wrapper. That is the feed is a JSON object which has a property called "results" which has the array. There might be additional properties on the feed object (next link, count, ...).
The versioning of the payload is based on the minimum version required by any feature in that payload. So if your service is using something which requires payload of version higher than V1, the entire payload will be written using that higher version.
You can see this even on the odata.org service - try this:
http://services.odata.org/OData/OData.svc/Products?$inlinecount=allpages&$format=json
The response will be V2 and will use the results wrapper.

Binding JSON to nested Grails Domain Objects

I'm developing a RESTful interface which is used to provide JSON data for a JavaScript application.
On the server side I use Grails 1.3.7 and use GORM Domain Objects for persistence. I implemented a custom JSON Marshaller to support marshalling the nested domain objects
Here are sample domain objects:
class SampleDomain {
static mapping = { nest2 cascade: 'all' }
String someString
SampleDomainNested nest2
}
and
class SampleDomainNested {
String someField
}
The SampleDomain resource is published under the URL /rs/sample/ so /rs/sample/1 points to the SampleDomain object with ID 1
When I render the resource using my custom json marshaller (GET on /rs/sample/1), I get the following data:
{
"someString" : "somevalue1",
"nest2" : {
"someField" : "someothervalue"
}
}
which is exactly what I want.
Now comes the problem: I try to send the same data to the resource /rs/sample/1 via PUT.
To bind the json data to the Domain Object, the controller handling the request calls def domain = SampleDomain.get(id) and domain.properties = data where data is the unmarshalled object.
The binding for the "someString" field is working just fine, but the nested object is not populated using the nested data so I get an error that the property "nest2" is null, which is not allowed.
I already tried implementing a custom PropertyEditorSupport as well as a StructuredPropertyEditor and register the editor for the class.
Strangely, the editor only gets called when I supply non-nested values. So when I send the following to the server via PUT (which doesn't make any sense ;) )
{
"someString" : "somevalue1",
"nest2" : "test"
}
at least the property editor gets called.
I looked at the code of the GrailsDataBinder. I found out that setting properties of an association seems to work by specifying the path of the association instead of providing a map, so the following works as well:
{
"someString" : "somevalue1",
"nest2.somefield" : "someothervalue"
}
but this doesn't help me since I don't want to implement a custom JavaScript to JSON object serializer.
Is it possible to use Grails data binding using nested maps? Or do I really heave to implement that by hand for each domain class?
Thanks a lot,
Martin
Since this question got upvoted several times I would like to share what I did in the end:
Since I had some more requirements to be implemented like security etc. I implemented a service layer which hides the domain objects from the controllers. I introduced a "dynamic DTO layer" which translates Domain Objects to Groovy Maps which can be serialized easily using the standard serializers and which implements the updates manually. All the semi-automatic/meta-programming/command pattern/... based solutions I tried to implement failed at some point, mostly resulting in strange GORM errors or a lot of configuration code (and a lot of frustration). The update and serialization methods for the DTOs are fairly straightforward and could be implemented very quickly. It does not introduce a lot of duplicate code as well since you have to specify how your domain objects are serialized anyway if you don't want to publish your internal domain object structure. Maybe it's not the most elegant solution but it was the only solution which really worked for me. It also allows me to implement batch updates since the update logic is not connected to the http requests any more.
However I must say that I don't think that grails is the appropriate tech stack best suited for this kind of application, since it makes your application very heavy-weight and inflexbile. My experience is that once you start doing things which are not supported by the framework by default, it starts getting messy. Furthermore, I don't like the fact that the "repository" layer in grails essentially only exists as a part of the domain objects which introduced a lot of problems and resulted in several "proxy services" emulating a repository layer. If you start building an application using a json rest interface, I would suggest to either go for a very light-weight technology like node.js or, if you want to/have to stick to a java based stack, use standard spring framework + spring mvc + spring data with a nice and clean dto layer (this is what I've migrated to and it works like a charm). You don't have to write a lot of boilerplate code and you are completely in control of what's actually happening. Furthermore you get strong typing which increases developer productivity as well as maintainability and which legitimates the additional LOCs. And of course strong typing means strong tooling!
I started writing a blog entry describing the architecture I came up with (with a sample project of course), however I don't have a lot of time right now to finish it. When it's done I'm going to link to it here for reference.
Hope this can serve as inspiration for people experiencing similar problems.
Cheers!
It requires you to provide teh class name:
{ class:"SampleDomain", someString: "abc",
nest2: { class: "SampleDomainNested", someField:"def" }
}
I know, it requires different input that the output it produces.
As I mentioned in the comment earlier, you might be better off using the gson library.
Not sure why you wrote your own json marshaller, with xstream around.
See http://x-stream.github.io/json-tutorial.html
We have been very happy with xstream for our back end (grails based) services and this way you can render marshall in xml or json, or override the default marshalling for a specific object if you like.
Jettison seems to produce a more compact less human readable JSON and you can run into some library collision stuff, but the default internal json stream renderer is decent.
If you are going to publish the service to the public, you will want to take the time to return appropriate HTTP protocol responses for errors etc... ($.02)