剑桥词典 Json 到数组
本文关键字:数组 Json | 更新日期: 2023-09-27 18:31:47
我正在使用此代码从剑桥词典网站获取JSon字符串。但我无法解析为字符串。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SkPublishAPI api = new SkPublishAPI("https://dictionary.cambridge.org/api/v1/", "MyaccessCode");
IList<IDictionary<string, object>> dictionaries = JsonToArray(api.GetDictionaries());
public class dictionaryNames
{
public string dictionaryName { get; set; }
public string dictionaryCode { get; set; }
public string dictionaryUrl { get; set; }
}
private static IDictionary<string, object> JsonToObject(string json)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
IDictionary<string, object> obj = jsonSerializer.Deserialize<IDictionary<string, object>>(json);
return obj;
}
private static IList<IDictionary<string, object>> JsonToArray(string json)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
IList<IDictionary<string, object>> array = jsonSerializer.Deserialize<IList<IDictionary<string, object>>>(json);
return array;
}
private static string ObjectToJson(object obj)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string json = jsonSerializer.Serialize(obj);
return json;
}
像这样的 Json 字符串响应
[
{
"dictionaryName": "Cambridge Advanced Learner's Dictionary",
"dictionaryCode": "british",
"dictionaryUrl": "http://dictionary.cambridge.org/dictionary/british/"
},
{
"dictionaryName": "Cambridge Learner's Dictionary English-Turkish",
"dictionaryCode": "turkish",
"dictionaryUrl": "http://dictionary.cambridge.org/dictionary/turkish/"
},
{
"dictionaryName": "Cambridge Dictionary of American English",
"dictionaryCode": "american-english",
"dictionaryUrl": "http://dictionary.cambridge.org/dictionary/american-english/"
},
{
"dictionaryName": "Cambridge Business English Dictionary",
"dictionaryCode": "business-english",
"dictionaryUrl": "http://dictionary.cambridge.org/dictionary/business-english/"
},
{
"dictionaryName": "Cambridge Learners Dictionary",
"dictionaryCode": "learner-english",
"dictionaryUrl": "http://dictionary.cambridge.org/dictionary/learner-english/"
}
]
如何反序列化此 Json 字符串。我尝试了很多,但我做不到。我没有编写反序列化代码,因为我是 C# 的新手。我在等你的帮助。谢谢
var dictionaries = new JavaScriptSerializer()
.Deserialize<List<dictionaryNames>>(json);
public class dictionaryNames
{
public string dictionaryName { get; set; }
public string dictionaryCode { get; set; }
public string dictionaryUrl { get; set; }
}
PS:您可以将JsonToObject
方法编写为:
private static T JsonToObject<T>(string json)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
T obj = jsonSerializer.Deserialize<T>(json);
return obj;
}
并用作:
List<dictionaryNames> dictionaries = JsonToObject<List<dictionaryNames>>(json);