我有将从服务器返回的字典,我将其转换为 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/>");
});
}
});
请您参考如下方法:
在它工作之前你必须做这些事情:
- 放一个
ScriptService归因于您的网络服务 - 放一个
ScriptMethod网络服务中的属性
如果这样做,您甚至不需要自己在服务器中解析创建 JSON。 WS 基础架构将为您完成。
然后,只需在客户端站点上使用 msg.d。它将自动从 JSOn 字符串反序列化。
看这里Using jQuery to Consume ASP.NET JSON Web Services了解您需要在客户端执行的操作。
Here you have a full working sample with client and server side .
请注意,在 ASP.NET 3.5 之前,响应消息会直接带来数据。在 3.5 及更高版本中,数据位于消息的 .d 属性中。
EDIT2:更简单的方法 我在第一次编辑中犯了一个错误:.asmx 无法将 Dictionay 序列化为 XML。因此,当我通过 .asmx 页面在第一次编辑中测试解决方案时,出现错误。但是 JSON 可以序列化一个以字符串或对象为键的字典。
因此,您可以使用此类来转换您的 Dictionary<int,string>至 Dictionary<string,string>使用这个通用类:
public class DictionaryConverter
{
public static Dictionary<string,TValue>
ConvertDictionary<TKey,TValue>(Dictionary<TKey,TValue> dict)
{
Dictionary<string,TValue> newDict
= new Dictionary<string, TValue>();
foreach(TKey key in dict.Keys)
{
newDict.Add(key.ToString(), dict[key]);
}
return newDict;
}
}
此类可以将具有任何键类型的任何字典转换为 Dictionary<string,Tvalue>字典,可以序列化为 JSON,但不能序列化为 XML。它使用 key 类型 toString()方法转换字符串中的键。这将非常适合 int和许多其他类型。如果需要,可以扩展此方法以接收将 key 转换为字符串的委托(delegate)。
在客户端,此解决方案与第一次编辑中的解决方案相同。第一次编辑的优点是它还可以支持序列化到 XML:您可以通过 .asmx 页面调用该方法,并将 WebMethod 用作常规 XML WebMethod。
编辑:在 .asmx 网络服务中序列化字典<>:
与 asmx 一起使用的序列化程序不支持XML 序列化字典。您可以创建一个自定义类并将您的字典转换为该自定义类的列表,该类具有一个键和一个值属性(序列化程序也不支持序列化 KeyValuePair 或 Tuple ,因此您必须使用自己的类)。
这个类有两个目的:
- 这是一个类,可以用asmx for JSON使用的序列化器序列化
允许转换类元素列表中的字典
public class KeyValue<TKey, TValue> { public KeyValue() { } public TKey Key { get; set; } public TValue Value { get; set; } public static List<KeyValue<TKey,TValue>> ConvertDictionary (Dictionary<TKey,TValue> dictionary) { List<KeyValue<TKey, TValue>> newList = new List<KeyValue<TKey, TValue>>(); foreach (TKey key in dictionary.Keys) { newList.Add(new KeyValue<TKey, TValue> { Key = key, Value = dictionary[key] }); } return newList; } }
您的网络方法应如下所示:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] // it's JSON by default
public List<KeyValue<int,string>> GetKeyValueList()
{
List<KeyValue<int, string>> list
= KeyValue<int,string>.ConvertDictionary(yourDictionary);
return list;
}
注意事项:
- 您可以使用任何方法名称代替
GetKeyValueList - TKey、TValue 必须与您的字典键和值类型相同。
在客户端,您会得到一个具有 Key 和 Value 属性的对象数组,可以像这样访问它们:
msg.d[0].Key
msg.d[0].Value
这是 jquery ajax 调用:
$(document).ready(function () {
$.ajax({
url: 'MyService.asmx/GetKeyValueList',
type: "POST",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
// use msg.d array of objects with Key and Value
}
});
});
