Sending a JSON request in C# using an HTTP POST

Hi all!  I need pointed in the right direction with something.  In C# on .Net 4.5, I need to send JSON to a REST API via an HTTP POST (running Windows on .Net 4.5 also).  The JSON details a single entity; the structure never changes.

Example:
{
  "A": "string",
  "B": " string ",
  "C": {
          "1": " string ",
          "2": " string ",
          "3": " string ",
          "4": {
                 "a":" string ",
                  "b":" string ",
                  "c":" string "
                    }
            }
}

The REST API responds back to the client with JSON.  This is part of a server deployment the client is running from, which is a one time action for the life of that server.  So client performance is not an issue.  I will have to build in other logic to allow for a retry if the REST API doesn’t return the object in a timely fashion.  Let’s say it will retry every 60 seconds for a few minutes before eventually timing out.

I’m looking for two things.  
1) What class should I use to make the connection to the REST API.  
2) Should I bother with anything other than a regular expression if the JSON strings I send over will always be formatted the same?

Thoughts on going about this, and do you have a sample or some webpages you can point me to?  I want to avoid using non-Microsoft shipped code if possible.  Using the HttpClient seems like a really good option; http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client.  But then there is WebRequest..  http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx.  

I’m a fairly novice programmer outside of some medium level scripting.  I’m not looking for anything too fancy.  
1974WidgetAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
käµfm³d 👽Connect With a Mentor Commented:
You're limiting yourself a tad by saying, "I want to avoid using non-Microsoft shipped code if possible." Nevertheless, one approach is to create a series of classes as I mentioned. Then you can use the DataContractJsonSerializer to serialize these classes into the appropriate JSON. You'll have to decorate your classes with some attributes in order to get the serialization to work, but it isn't too complicated:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace _28599653
{
    class Program
    {
        static void Main(string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Root));
            Root instance = new Root() { A = "string", B = "string", C = new Child() { One = "string", Two = "string", Three = "string", Four = new ChildChild() { a = "string", b = "string", c = "string" } } };
            MemoryStream ms = new MemoryStream();
            string json;

            serializer.WriteObject(ms, instance);
            ms.Position = 0;
            json = Encoding.UTF8.GetString(ms.ToArray());
            System.Diagnostics.Debugger.Break();
        }

        [DataContract]
        public class Root
        {
            [DataMember]
            public string A { get; set; }
            [DataMember]
            public string B { get; set; }
            [DataMember]
            public Child C { get; set; }
        }

        [DataContract]
        public class Child
        {
            [DataMember(Name = "1")]
            public string One { get; set; }
            [DataMember(Name = "2")]
            public string Two { get; set; }
            [DataMember(Name = "3")]
            public string Three { get; set; }
            [DataMember(Name = "4")]
            public ChildChild Four { get; set; }
        }

        [DataContract]
        public class ChildChild
        {
            [DataMember]
            public string a { get; set; }
            [DataMember]
            public string b { get; set; }
            [DataMember]
            public string c { get; set; }
        }
    }
}

Open in new window


In the above, you can see that I create a "Root" class which the overarching structure for the entire object. The name is really inconsequential; I used "Root" just as an example. From there, you trace down the JSON hierarchy to add to this object properties which correspond to those found in the JSON. Each time in the JSON that you get to a property which is not a simple type (e.g. string, int, date), you introduce a new class. That is what I'm doing with "Child" and "ChildChild". Again, the names are only for example, and you can either change them directly, or use the DataContract's Name property to override what the serializer would normally output.
0
 
käµfm³d 👽Connect With a Mentor Commented:
What class should I use to make the connection to the REST API.
Either of the two classes you mention should do the job. There is also the WebClient class available. It's a bit easier to use than HttpClient, but you lose some of the granularity and control for the sake of the ease.

Should I bother with anything other than a regular expression if the JSON strings I send over will always be formatted the same?
I don't see what regular expressions have to do with this task. Myself, I would create a class structure to mimic the JSON structure, and then rely on serialization to transform a class instance in memory into JSON over the wire. However, it's unclear as to whether or not you need that. Can you clarify:  is it the structure only that is constant, or is the data itself constant as well?
0
 
1974WidgetAuthor Commented:
The structure is constant.  The data itself won't be.
0
 
NavneetConnect With a Mentor Software EngineerCommented:
Try this way to Get and Post Json data to API and get JSON result.
from : http://openweathermap.org/

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            var relativeUri = "data/2.5/weather?q=London,uk";

            //get
            var sendGetResult = GetSendRequest(relativeUri);

            //post
            var Requestor = new Employee { Id = 1, Name = "Navneet" };

            string jsonRequester = new JavaScriptSerializer().Serialize(Requestor);
            var sendPostResult = PostSendRequest(relativeUri, jsonRequester);

        }

        private class Employee
        {
            public Employee() { }

            public int Id { get; set; }
            public string Name { get; set; }

        }

        static Dictionary<string, dynamic> GetSendRequest(string relativeUri)
        {
            var ServiceUri = "http://api.openweathermap.org/";
            var response = new Dictionary<string, dynamic>();
            try
            {
                var client = new HttpClient { BaseAddress = new Uri(ServiceUri) };
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage responseMessage = null;
                responseMessage = client.GetAsync(relativeUri).Result;

                HttpStatusCode statusCode;
                Enum.TryParse(responseMessage.StatusCode.ToString(), out statusCode);

                var result = responseMessage.Content.ReadAsStringAsync().Result;

                if (statusCode != HttpStatusCode.OK)
                {
                    //send error response
                }

                response = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(result);
                return response;
            }
            catch (Exception)
            {
                throw;
            }
        }


        static Dictionary<string, dynamic> PostSendRequest(string relativeUri, object postData)
        {
            var ServiceUri = "http://api.openweathermap.org/";
            var response = new Dictionary<string, dynamic>();
            try
            {
                var client = new HttpClient { BaseAddress = new Uri(ServiceUri) };
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage responseMessage = null;
                responseMessage = client.PostAsJsonAsync(relativeUri, postData).Result;

                HttpStatusCode statusCode;
                Enum.TryParse(responseMessage.StatusCode.ToString(), out statusCode);

                var result = responseMessage.Content.ReadAsStringAsync().Result;

                if (statusCode != HttpStatusCode.OK)
                {
                    //send error response
                }

                response = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(result);
                return response;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Open in new window


Thanks!
Navneet
0
 
1974WidgetAuthor Commented:
Thanks all!  I haven't tried these yet, but this get's me started down the proper path.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.