我只是使用XmlWriter创建了一些XML,以便在HTTP响应中发回。如何创建JSON字符串?我猜你会使用stringbuilder来构建JSON字符串,然后将响应格式化为JSON?
当前回答
这个库非常适合用于c#中的JSON
http://james.newtonking.com/pages/json-net.aspx
其他回答
如果你需要复杂的结果(嵌入),创建你自己的结构:
class templateRequest
{
public String[] registration_ids;
public Data data;
public class Data
{
public String message;
public String tickerText;
public String contentTitle;
public Data(String message, String tickerText, string contentTitle)
{
this.message = message;
this.tickerText = tickerText;
this.contentTitle = contentTitle;
}
};
}
然后通过调用获取JSON字符串
List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");
string json = new JavaScriptSerializer().Serialize(request);
结果是这样的:
json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"
希望能有所帮助!
DataContractJSONSerializer将像XMLSerializer一样简单地为您做所有事情。在web应用程序中使用它很简单。如果你正在使用WCF,你可以用一个属性指定它的用途。DataContractSerializer系列也非常快。
看看http://www.codeplex.com/json/上的json-net。aspx项目。为什么要重新发明轮子?
如果您试图创建一个web服务,通过JSON向web页面提供数据,请考虑使用ASP。. NET Ajax工具包:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
它会自动将你通过webservice服务的对象转换为json,并创建你可以用来连接到它的代理类。
你也可以试试我的ServiceStack JsonSerializer,它是目前最快的。net JSON序列化器。它支持序列化数据契约、任何POCO类型、接口、晚期绑定对象(包括匿名类型)等。
基本的例子
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
注意:如果性能对您来说不重要,请只使用microsoft JavaScriptSerializer,因为它比其他JSON序列化器慢了40 -100倍,所以我不得不将它排除在基准测试之外。
推荐文章
- 如何合并2 JSON对象从2个文件使用jq?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- <system. >之间的差异。web>和<system.webServer>?
- 为什么ASP。NET web表单需要Runat="Server"属性吗?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?
- csproj文件中的“Service Include”是干什么用的?