如何从JSON请求发回数据

时间:2011-03-07 15:17:59

标签: c# vb.net web-services json

我有一个现有的WSDL,它使用SOAP将信息返回给远程设备。但是,我正在用Android编写一个新的应用程序,它不支持SOAP,所以我不能使用现有的WSDL,并且必须编写一个新的应用程序,它从Android应用程序中查找查询字符串并以JSON格式返回数据包。我编写了接收数据的模块,但是我不确定如何以JSON格式发送数据,是否有人在VB.Net或C#中有任何示例,它向我展示了如何将数据返回给JSON请求者?

1 个答案:

答案 0 :(得分:2)

您会很高兴知道.NET使用DataContractJsonSerializer使这非常简单。这是从HTTP处理程序中提取的一些代码。 MyDataType是可序列化类的名称。

context.Response.ContentType = "application/json";
MyDataType someObject = new MyDataType();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyDataType));
using (MemoryStream ms = new MemoryStream())
{
    ser.WriteObject(ms, data);
    ms.Seek(0, SeekOrigin.Begin);

    StreamReader sr = new StreamReader(ms);
    string json = sr.ReadToEnd();
    Trace("Returning JSON:\n" + json + "\n");
    context.Response.Write(json);
}

This is我在必须这样做时使用的主要博文。