从C#将数据传递给Json

时间:2018-09-05 10:20:00

标签: c# json

对于JSON和webapi来说确实是新的。我想将一些数据传递到JSON URL,并将数据作为c#对象取回。到目前为止,我在网上可以找到的信息远远少于我找到的信息,或者没有达到我的信息。我不知道如何传递价值。 “ URL / importSet”在这里对importset的含义是什么。

city

而我的json数据格式为:

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());
}

任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:2)

为了将对象作为json传递,您可以使用NuGet程序包管理器中可用的程序包Newtonsoft

using Newtonsoft.Json;

您将按以下方式使用它:

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

var dataJson = JsonConvert.SerializeObject(data);

这给出了:

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

然后可以在请求中使用:

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

现在,当您收到结果时,只需在创建一个代表您要接收的内容的类后使用Deserialize

答案 1 :(得分:0)

简单,您可以使用Newtonsoft库进行序列化和反序列化 用途:使用Newtonsoft.Json;

喜欢:

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;
    }

有关更多信息,请参见Newtonsoft

或者,如果您想在URL中插入数据并在其他页面中使用该数据,则必须创建QueryString以获取更多信息,请参见this

HttpRequest类代表对服务器的请求,并具有与之相关的各种属性,例如QueryString

ASP.NET运行时将请求解析到服务器,并为您填充此信息。

阅读HttpRequest属性,获取由ASP.NET代表您填充的所有潜在属性的列表。

注意:并非所有属性都会被填充,例如,如果您的请求没有查询字符串,则QueryString将为空/空。因此,在像这样使用它之前,您应该检查一下查询字符串中是否确实存在期望的内容:

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

答案 2 :(得分:0)

谢谢大家的支持。下面是为我工作的代码,现在我可以得到响应了。

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);
            }