我有这样的课程:
class MyDate
{
int year, month, day;
}
class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}
Run Code Online (Sandbox Code Playgroud)
我想将一个Lad对象变成一个像这样的JSON字符串:
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
Run Code Online (Sandbox Code Playgroud)
(没有格式化).我找到了这个链接,但它使用的是一个不在.NET 4中的命名空间.我也听说过JSON.NET,但是他们的网站目前似乎已经关闭了,我并不热衷于使用外部DLL文件.除了手动创建JSON字符串编写器之外还有其他选项吗?
这是我正在使用的代码:
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out …Run Code Online (Sandbox Code Playgroud) 我正在用C#编写一个小工具,它需要使用POST和json格式向网站发送数据和从网站接收数据.我以前从未在C#(或任何语言)中做过这样的事情,所以我很难找到一些有用的信息让我开始.
我在C#中找到了一些关于WebRequest类的信息(特别是从这里开始),但在我开始深入研究之前,我想知道这是否适合这项工作.
我发现有很多工具可以将数据转换为json格式,但其他方面并不多,所以任何信息在这里都会非常有用,以防我最终陷入死胡同.
我是C#和Windows手机的新手,我正在尝试创建一个执行JSON请求的小应用程序.我正在关注此帖子中的示例/sf/answers/349216661/
我目前的代码是这样的:
public string login()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(MY_URL);
httpWebRequest.ContentType = "text/plain";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string text = MY_JSON_STRING;
streamWriter.Write(text);
}
}
Run Code Online (Sandbox Code Playgroud)
但由于某些原因,Visual Studio正在标记GetRequestStream()错误消息:
错误CS1061:'System.Net.HttpWebRequest'不包含'GetRequestStream'的定义,并且没有可以找到接受类型'System.Net.HttpWebRequest'的第一个参数的扩展方法'GetRequestStream'(您是否缺少using指令或装配参考?)
有关为什么会发生这种情况的任何想法?我已经导入了System.Net包.