Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 147
  • Last Modified:

reading json from C# REST service

Hi, I have recently created a REST service using C# console and OWIN.    It works fine but I wan't to take it a step further and I don't know how I can achieve my goal.    

Below is my code, as you can see I'm using ApiController to read the json data received.    What I would achieve is to read the json variable "type" to know what I have received and then depending if it's a customer, product or else I would like to read the variable "content" knowing what to expect so I can cast "content" as a Customer object for instance.

The actual json content I would like to send is this, I can read the "type" field but I don't know how to get "content" and send the values to the "customer" object I have.   I'm pretty sure it can be done, it's a matter of getting the POST parameter, analyse it and read it as a json content.    Currently I can only achieve reading json as a content automatically when receiving a POST command.

    {
        "type": "customer",
        "content": {          
          "Name": "test",
          "Adress": "test adress",
          }
    }

Here is the APIController:

    public class MyApiController : ApiController
    {
        public void Post(JsonStruct json)     // [FromBody]
        {
        if (json.type.Equals("customer", StringComparison.OrdinalIgnoreCase))
             {
                    // read content as a Customer class
        }
       }
    }      

Here is the expected fields:
    public class JsonStruct
    {
        public string type { get; set; }
        public Stream content { get; set; }
    }

Here is an example of Customer record I would like to build:
    public class Customer
    {
        public string name { get; set; }
        public string adress { get; set; }
    }
0
Buropro-Citation
Asked:
Buropro-Citation
1 Solution
 
zephyr_hex (Megan)DeveloperCommented:
The way I've handled this in the past is to create a class that mimics the structure of the JSON.  There's actually an online tool that will help you construct the class based on the JSON:

http://json2csharp.com/


You can then deserialize using JSON.NET
1

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now