我在 .NET 框架中没有找到解析 JSON 字符串的简单方法,虽然有 Newtonsoft.Json 这种东西,但它太重,所以想自己造个轮子。
对于以下这种简单的 JSON 字符串:
{
"error": {
"code": "request_token_invalid",
"message": "The access token isn't valid."
}
}
给定一个方法,传入字符串和键,返回对应的值。
public static string JsonToValue(string json,string key) {
// Todo
}
我的思路是遍历字符串,找到所有双引号的位置,然后把这些字符串取出存入列表,位于 key 后面的字符串就是要找的值。
public static string JsonToValue(string json,string key) {
var index = new List<int>();
for (int i = 0; i < json.Length; i++) {
if (json[i] == '"') index.Add(i);
}
var str = new List<string>();
for (int i = 0; i < index.Count; i++) {
str.Add(json.Substring(index[i] + 1,index[i + 1] - index[i] - 1));
i++;
}
for (int i = 0; i < str.Count; i++) {
if (str[i] == key) return str[i + 1];
}
return null;
}
但是这种方法太繁琐了,大家还有没有更好的思路?
内置方式:使用.NET Framework 3.5/4.0中提供的System.Web.Script.Serialization命名空间下的JavaScriptSerializer类进行对象的序列化与反序列化,很直接。
契约方式:使用System.Runtime.Serialization.dll提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现。