Parsing Json.Net Web Api

I am new to the Web API 2 / Entity Framework 6 project, I create REST services, but for one specific service I am going to receive (via Post) JSON before performing any CRUD operations on any model object (you need to do some business checks on the data, add or complement some things and decide which object to save), JSON:

{ "head": { "action": "create", "object": "oneobject", "user": "theuser" }, "object": { "name1": "a name 1", "name2": "a name 2", "description": "a description here" }, "rule": [{ "name": "any name", "value": "any value" }, { "name": "another name", "value": "another value" }] } 

Thus, json is not directly mapped to an entity; in fact, I don't have a model or object for this. What would be the best way to work with him? I mean how to get and parse json. I am new to api and rest web services and I would appreciate that you can help me and explain me some good details. Thanks guys.

Edit:

  • Any POCO or class idea that matches this kind of json. (list "rule". This variable can be one or more).

  • After creating this poco or class, would I have to create a controller based on this?

0
json c # rest entity-framework asp.net-web-api2
May 25 '16 at 20:53
source share
4 answers

As others have said, you need a POCO object to represent your request. Based on the information that you have provided, you should achieve fairly close to what you then:

 public enum CrudAction { Create, Read, Update, Delete } public sealed class CrudRequestHeader { public CrudAction Action { get; set; } public string Object { get; set; } public string User { get; set; } } public sealed class RuleDefinition { public string Name { get; set; } public string Value { get; set; } } public sealed class CrudRequest { public CrudRequestHeader Head { get; set;} public Dictionary<string, string> Object { get; set; } public List<RuleDefinition> Rule { get; set; } } 

In your web API controller method, you can take a parameter of type CrudRequest , and your JSON will be deserialized for this object, for example:

 public IHttpActionResult Post(CrudRequest crudRequest) { // TODO Implementation } 

You may notice that I used Dictionary<string, string> for CrudRequest.Object , since it is a variable number of keys / values ​​that we will supply with, I made the assumption that all values ​​are strings, you can use the value of object if you prefer, but you will need to handle the type of value. In the same principle, I used List<RuleDefinition> for CrudRequest.Rule to serve a variable number of rules that can be provided.

A LINQPad sample containing the above definitions and using it can be found here: http://share.linqpad.net/7rvmhh.linq

+2
May 25 '16 at 22:22
source share
β€” -

It would be best to create a class that models the object you expect.

Thus, in your Web API method, you can use the [FromBody] attribute to automatically analyze the request body.

Example -

Your data contract will look like this:

 public class MyContract { public string MyData { get; set;} } 

In your ApiController

 [HttpPost] [Route("api/myobject")] public async Task ReceiveMyObject([FromBody]MyContract object) { var data = object.MyData; // Do whatever you need to do here. } 

This may seem tedious, but it will allow you to save your code.

Edit So, to create a contract from this:

 { "head": { "action": "create", "object": "oneobject", "user": "theuser" }, "object": { "name1": "a name 1", "name2": "a name 2", "description": "a description here" }, "rule": [{ "name": "any name", "value": "any value" }, { "name": "another name", "value": "another value" }] } 

You would do something like this:

 public class MyContract { [JsonProperty("head")] public MetaObject Head { get; set; } // Not sure if this will work, but it probably will [JsonProperty("object")] public JObject ExtendedInformation { get; set; } [JsonProperty("rule")] public Rule[] Rules { get; set; } } // "MetaObject" definition omitted but you can understand my point with the below public class Rule { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("value")] public string Value { get; set; } } 
+2
May 25 '16 at 21:11
source share

Although JSON cannot be a logical object in your model, you obviously have a mental model of the "form" of JSON data - I say this because you define it in your code snippet. You must create a POCO (plain old C # object) to represent this model and deserialize the incoming JSON request to an object of this type. Once you separate it from an object to an object, it will be trivial to work with this data using the properties of the object, etc.

+1
May 25 '16 at 21:10
source share

Usually, the REST service issues a contract, which means some kind of metadata to describe the contents of its messages, otherwise you cannot call it a RESTful Web API. Take a look at this post from Roy Fielding, who coined the term REST API if you want to know better what REST is and what not.

So, if your service is a true REST service, you should have somewhere a description that will give you the opportunity to analyze the media.

However, if you still cannot find a way to understand how JSON should be interpreted, you can use it inside the C # class anyway: take a look at the JObject class, which allows you to use a dynamic object at runtime.

It is mainly used as follows:

 using Newtonsoft.Json.Linq; // This needs the Newtonsoft.Json package dynamic entity = JObject.Parse(jsonString); string value = entity.key1; string value2 = entity["key2"]; 

I made this simple demo with your data.

You can also check the full class documentation on the Newtonsoft website.

0
May 25 '16 at 21:55
source share



All Articles