我有将从服务器返回的字典,我将其转换为 json 字符串格式,如下所示:
public static class Extensions
{
public static string ToJson<T>(this T obj)
{
MemoryStream stream = new MemoryStream();
try {
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
jsSerializer.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
finally
{
stream.Close();
stream.Dispose();
}
}
public static T FromJson<T>(this string input)
{
MemoryStream stream = new MemoryStream();
try {
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
T obj = (T)jsSerializer.ReadObject(stream); return obj;
}
finally
{
stream.Close();
stream.Dispose();
}
}
}
[WebMethod]
public string callme()
{
Dictionary<int, string> myObjects = new Dictionary<int, string>();
myObjects.Add(1, "This");
myObjects.Add(2, "is");
myObjects.Add(3, "cool");
string json = myObjects.ToJson();
return json;
}
所以结果是:
{"d":"[{\"Key\":1,\"Value\":\"This\"},{\"Key\":2,\"Value\":\"is\"},{\"Key\":3,\"Value\":\"cool\"}]"}
我如何在 jquery 中解析它?我正在尝试这个但没有帮助
$.ajax({
type: "POST",
url: "web.asmx/callme",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg){
$.each(msg.d, function (i) {
$("#data2").append(i.Key + " " + i.Value + "<br/>");
});
}
});