paip.C#.NET JSON解析总结
作者Attilax , EMAIL:1466519819@qq.com
近日做跑号器,需要解析JSON
{"code":799,"data":{"backUrl":""},"message":"\u767b\u9646\u6210\u529f"}
查了下资料,有原生API可解析,可惜要3.0以上,,为了兼容性,我的程序是2.0的..
只好用类库Newtonsoft.Json.dll..
去官网下载2.0的.但是它实际上引用的.NET版是3.5的..因为用到了LINQ.. 将其源码下载下来,把LINQ全替换掉,编译时,需要SYSTEM.CORE.DLL..而这个DLL也是3.5的..没办法..
只好下载1.3.1的...
调用的时候.
// JObject jo = JObject.Parse(jsonText);
//// JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
// string zone = jo["code"] .ToString();
这两句都出错,找不到类..实际上这两个语法应该是Newtonsoft.Json.dll 2.0的写法吧,不适合1.3.1
只好用其JsonReader来读了,这个类比较底层些.顺利读出属性值 .
完整解析:
================
while (reader.Read())
{
// zone += "TokenType = " + reader.TokenType + " ValueType = " + reader.ValueType + " Value = " + reader.Value + "\r\n";
}
TokenType = StartObject ValueType = Value =
TokenType = PropertyName ValueType = System.String Value = code
TokenType = Integer ValueType = System.Int64 Value = 799
TokenType = PropertyName ValueType = System.String Value = data
TokenType = StartObject ValueType = Value =
TokenType = PropertyName ValueType = System.String Value = backUrl
TokenType = String ValueType = System.String Value =
TokenType = EndObject ValueType = Value =
TokenType = PropertyName ValueType = System.String Value = message
TokenType = String ValueType = System.String Value = 767b96466210529f
TokenType = EndObject ValueType = Value =
自定义封装:
----------------------
上面的代码太底层,所以需要封装一下,以便使用,.此外..比如需要读取CODE这个属性值就可以了..
String zone = jsonC41.getProperty("code", jsonText);
public static string getProperty(string PropertyName, String jsonText)
{
JsonReader reader = new JsonReader(new StringReader(jsonText));
string zone = "";
bool getProperName = false;
while (reader.Read())
{
// zone += "TokenType = " + reader.TokenType + " ValueType = " + reader.ValueType + " Value = " + reader.Value + "\r\n";
if (getProperName)
{
zone = reader.Value.ToString().Trim();
break;
}
if (reader.TokenType.ToString().Equals("PropertyName"))
if (reader.Value != null)
if (reader.Value.Equals(PropertyName))
getProperName = true;
}
return zone;
}
参考:
C#解析json文件的方法 - 方倍 - 博客园.htm
Newtonsoft.Json.dll使用 - 东名夜雨 的专栏 - 博客频道 - CSDN.NET.htm