【发布时间】:2010-11-06 13:37:05
【问题描述】:
我刚刚使用 XmlWriter 创建了一些 XML 以在 HTTP 响应中发回。您将如何创建 JSON 字符串。我假设您只会使用字符串构建器来构建 JSON 字符串,然后它们会将您的响应格式化为 JSON?
【问题讨论】:
我刚刚使用 XmlWriter 创建了一些 XML 以在 HTTP 响应中发回。您将如何创建 JSON 字符串。我假设您只会使用字符串构建器来构建 JSON 字符串,然后它们会将您的响应格式化为 JSON?
【问题讨论】:
使用Newtonsoft.Json 会更容易:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
【讨论】:
string json = JsonConvert.SerializeObject(new { "PropertyA" = obj.PropertyA });.
"PropertyA" 不应该是 PropertyA 吗?
string json = JsonConvert.SerializeObject(new { PropertyA = obj.PropertyA });,PropertyA. 上没有双引号
您可以使用JavaScriptSerializer class,检查this article 来构建一个有用的扩展方法。
文章代码:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
用法:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
【讨论】:
Newtonsoft.Json 和 Newtonsoft.Json.Linq 库的简单使用。
//Create my object
var myData = new
{
Host = @"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string jsonData = JsonConvert.SerializeObject(myData);
//Print the Json object
Console.WriteLine(jsonData);
//Parse the json object
JObject jsonObject = JObject.Parse(jsonData);
//Print the parsed Json object
Console.WriteLine((string)jsonObject["Host"]);
Console.WriteLine((string)jsonObject["UserName"]);
Console.WriteLine((string)jsonObject["Password"]);
Console.WriteLine((string)jsonObject["SourceDir"]);
Console.WriteLine((string)jsonObject["FileName"]);
【讨论】:
这个库非常适合来自 C# 的 JSON
【讨论】:
此代码 sn-p 使用 .NET 3.5 中 System.Runtime.Serialization.Json 中的 DataContractJsonSerializer。
public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
{
serializer.WriteObject(writer, value);
}
return encoding.GetString(stream.ToArray());
}
}
【讨论】:
您也可以试试我的 ServiceStack JsonSerializer,目前是 fastest .NET JSON serializer。它支持序列化 DataContracts、任何 POCO 类型、接口、包括匿名类型在内的后期绑定对象等。
基本示例
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
注意:仅当性能对您不重要时才使用 Microsoft 的 JavaScriptSerializer,因为我不得不将它排除在我的基准测试之外,因为它比其他 JSON 序列化程序慢 40x-100x。
【讨论】:
如果您需要复杂的结果(嵌入式)创建自己的结构:
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-net.aspx 项目的 http://www.codeplex.com/json/。为什么要重新发明轮子?
【讨论】:
如果您不能或不想使用两个内置 JSON 序列化程序(JavaScriptSerializer 和 DataContractJsonSerializer),您可以尝试使用 JsonExSerializer 库 - 我在许多项目和作品中使用它很好。
【讨论】:
如果您尝试创建 Web 服务以通过 JSON 向网页提供数据,请考虑使用 ASP.NET Ajax 工具包:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
它会自动将通过 web 服务提供的对象转换为 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.Dynamic 命名空间。
【讨论】:
DataContractJSONSerializer 将像 XMLSerializer 一样简单地为您完成所有工作。在网络应用程序中使用它很简单。如果您使用的是 WCF,则可以通过属性指定其用途。 DataContractSerializer 系列也非常快。
【讨论】:
我发现您根本不需要序列化程序。如果您将对象作为列表返回。 让我举个例子。
在我们的 asmx 中,我们使用传递的变量获取数据
// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id)
{
var data = from p in db.property
where p.id == id
select new latlon
{
lat = p.lat,
lon = p.lon
};
return data.ToList();
}
public class latlon
{
public string lat { get; set; }
public string lon { get; set; }
}
然后我们使用 jquery 访问服务,传递该变量。
// get latlon
function getlatlon(propertyid) {
var mydata;
$.ajax({
url: "getData.asmx/GetLatLon",
type: "POST",
data: "{'id': '" + propertyid + "'}",
async: false,
contentType: "application/json;",
dataType: "json",
success: function (data, textStatus, jqXHR) { //
mydata = data;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
return mydata;
}
// call the function with your data
latlondata = getlatlon(id);
我们得到了回应。
{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
【讨论】:
编码用法
简单对象转 JSON 数组 EncodeJsObjectArray()
public class dummyObject
{
public string fake { get; set; }
public int id { get; set; }
public dummyObject()
{
fake = "dummy";
id = 5;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
sb.Append(id);
sb.Append(',');
sb.Append(JSONEncoders.EncodeJsString(fake));
sb.Append(']');
return sb.ToString();
}
}
dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();
dummys[0].fake = "mike";
dummys[0].id = 29;
string result = JSONEncoders.EncodeJsObjectArray(dummys);
结果: [[29,"mike"],[5,"dummy"]]
漂亮的用法
Pretty print JSON Array PrettyPrintJson() 字符串扩展方法
string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();
结果是:
[
14,
4,
[
14,
"data"
],
[
[
5,
"10.186.122.15"
],
[
6,
"10.186.122.16"
]
]
]
【讨论】:
包括:
使用 System.Text.Json;
然后像这样序列化你的 object_to_serialize: JsonSerializer.Serialize(object_to_serialize)
【讨论】: