C# 中的 JSON;发送和接收数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2077265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON in C#; Sending and receiving data
提问by Pankaj Mishra
I am trying to make a desktop client for Request and Response application.
我正在尝试为请求和响应应用程序制作桌面客户端。
I am able to do GET requests easily. But I was wondering whether someone could help me work out how I could do a JSON request and response. and parse it to a string, from there I can workout how to slit it all up
我能够轻松地进行 GET 请求。但我想知道是否有人可以帮助我弄清楚如何进行 JSON 请求和响应。并将其解析为字符串,从那里我可以练习如何将其全部切开
回答by anonymous coward
Look into the System.Web.Script.Serialization.JavaScriptSerializerclass in the System.Web.Extensions.dll assembly.
查看System.Web.Extensions.dll 程序集中的System.Web.Script.Serialization.JavaScriptSerializer类。
It contains the Serialize and Deserialize< T > methods which are fairly straight-forward to use.
它包含 Serialize 和 Deserialize<T> 方法,使用起来非常简单。
回答by Chris S
Small update:
小更新:
As an alternative to System.Web or JSON.net, there's also JSONFXand ServiceStack.Text
作为 System.Web 或 JSON.net 的替代方案,还有JSONFX和ServiceStack.Text
For a desktop application one solution for making a JSON request is below. There may be an API somewhere to already do this but I haven't found any.
对于桌面应用程序,发出 JSON 请求的一种解决方案如下。某处可能有一个 API 可以做到这一点,但我还没有找到。
The desktop app
桌面应用程序
'Test' is just here to demonstrate passing parameters. JavaScriptSerializer
is found in System.Web.Extensions.dll.
“测试”只是为了演示传递参数。JavaScriptSerializer
在 System.Web.Extensions.dll 中找到。
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create("http://localhost:2616/Default.aspx/JsonTester");
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("{id : 'test'}");
}
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json += reader.ReadLine();
}
}
// 3.5+ adds 'D' to the result, e.g.
// {"d":"{\"Name\":\"bob\",\"Age\":20,\"Foods\":[\"cheeseburger\",\"caviar\"]}"}
// So it thinks it's a dictionary with one key/value
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);
MyData data = serializer.Deserialize<MyData>(x["d"].ToString());
Default.aspx in the ASP.NET webapplication:
ASP.NET Web 应用程序中的 Default.aspx:
[WebMethod]
public static string JsonTester(string id)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new MyData()
{
Name = "bob",
Age = 20,
Foods = new List<string>()
};
jsonData.Foods.Add("cheeseburger");
jsonData.Foods.Add("caviar");
var result = ser.Serialize(jsonData);
return result;
}
The MyData object
MyData 对象
MyData
appears in both the web app and the console app, but you'll want to put it in its own assembly as your domain object and reference it in the two places.
MyData
出现在 web 应用程序和控制台应用程序中,但您需要将它作为域对象放在自己的程序集中,并在两个地方引用它。
public class MyData
{
public string Name { get; set; }
public int Age { get; set; }
public IList<String> Foods { get; set; }
}