我只是使用XmlWriter创建了一些XML,以便在HTTP响应中发回。如何创建JSON字符串?我猜你会使用stringbuilder来构建JSON字符串,然后将响应格式化为JSON?
当前回答
如果你想避免创建一个类和创建JSON,那么创建一个动态对象和序列化对象。
dynamic data = new ExpandoObject();
data.name = "kushal";
data.isActive = true;
// convert to JSON
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
读取JSON并像这样反序列化:
// convert back to Object
dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
// read a particular value:
output.name.Value
ExpandoObject来自System。动态名称空间。
其他回答
看看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,并创建你可以用来连接到它的代理类。
包括:
使用System.Text.Json;
然后像这样序列化你的object_to_serialize: JsonSerializer.Serialize (object_to_serialize)
如果你需要复杂的结果(嵌入),创建你自己的结构:
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\"}}"
希望能有所帮助!
如果你不能或不想使用两个内置的JSON序列化器(JavaScriptSerializer和DataContractJsonSerializer),你可以尝试JsonExSerializer库——我在许多项目中使用它,工作得很好。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 查询JSON类型内的数组元素
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 将JSON字符串转换为HashMap
- 将JsonNode转换为POJO
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?