NAJEEB
NAJEEB

Reputation: 251

Pass the data to Json from C#

Really new to JSON and webapi. I want to pass some data to JSON URL and get the data back as a c# object. so far what i can find online is below no much information I found or i am not reached. I don't know how to pass the value. "URL/importSet" what is the meaning here for importset.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL/importSet");

IWebProxy theProxy = request.Proxy;

if (theProxy != null)
{
    theProxy.Credentials = CredentialCache.DefaultCredentials;
}

CookieContainer cookies = new CookieContainer();
request.UseDefaultCredentials = true;
request.CookieContainer = cookies;
request.ContentType = "application/json";
request.CookieContainer = cookies;

// write the "Authorization" header
request.Headers.Add("Authorization", "Bearer " + "token-key001");
request.Method = "POST";
var data = new {"I try to copy paste the json data here what i mention down"}
byte[] postBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postBytes.Length;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    StreamReader reader = new StreamReader(response.GetResponseStream());
    Console.Write(reader.ReadToEnd());
}

and my json data format is :

 {
    "BasicInformation": {
        "BranchName": "ABC",
        "DateFrom": "20180905",
        "DateTo": "20180905"
    },

    "Details": "",
    "Header": {
        "Company": "C001",
        "BranchCode": "ABC123"
    }
}

Any help will be grateful. Thanks.

Upvotes: 1

Views: 2082

Answers (3)

AmirReza-Farahlagha
AmirReza-Farahlagha

Reputation: 1212

Simple, You can use of Newtonsoft liberary for serialize and deserialize Use: using Newtonsoft.Json;

like:

public T Deserialize()
    {
        var jsonData = "Your string JSON data";

        var objectJSON = JsonConvert.DeserializeObject<T>(jsonData);

        return objectJSON;
    }

    public T Serialize()
    {
        var objectData = new Student();

        var objectData = JsonConvert.SerializeObject(objectData);

        return objectData;
    }

For more Information see Newtonsoft

Or If you want to insert data in your URL and use of that in other pages, you have to create QueryString for more information see this

The HttpRequest class represents the request made to the server and has various properties associated with it, such as QueryString.

The ASP.NET run-time parses a request to the server and populates this information for you.

Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.

Note: not all properties will be populated, for instance if your request has no query string, then the QueryString will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:

if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
   // Query string value is there so now use it
   int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}

Upvotes: 0

NAJEEB
NAJEEB

Reputation: 251

Thank you for all support me. below is the code work for me, now I can get the response.

try
            {
                string webAddr = "URL/ImportSet";

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
                httpWebRequest.Headers.Add("Authorization", "Bearer " + "TOKEN NO");
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method = "POST";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"BasicInformation\":{\"BranchName\":\"Abc\",\"DateFrom\":\"20180905\",\"DateTo\":\"20180905\"},\"Details\":\"\",\"Header\":{\"Company\":\"C001\",\"BranchCode\":\"ABC123\"}}";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                }
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    textBox1.Text = responseText.ToString();

                }
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }

Upvotes: 0

Haytam
Haytam

Reputation: 4733

In order to pass an object as json, you can use the package Newtonsoft available in the NuGet package manager.

using Newtonsoft.Json;

You'll use it as follow:

var data = new {
    BasicInformation = new {
        BranchName = "ABC",
        DateFrom = "20180905",
        DateTo = "20180905"
    },
    Details = "",
    Header = new {
        Company = "C001",
        BranchCode = "ABC123"
    }
};

var dataJson = JsonConvert.SerializeObject(data);

This gives:

{"BasicInformation":{"BranchName":"ABC","DateFrom":"20180905","DateTo":"20180905"},"Details":"","Header":{"Company":"C001","BranchCode":"ABC123"}}

Which you can then use in your request:

byte[] postBytes = Encoding.ASCII.GetBytes(dataJson);

Now when you receive the result, just use Deserialize after creating a class that represents what you're receiving.

Upvotes: 2

Related Questions