日期:2014-05-16 浏览次数:20411 次
using System; using System.Collections.Generic; using System.Web; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Json; //添加引用System.Runtime.Serialization namespace QAPITool { public static class JSON { public static T parse<T>(string jsonString) { using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString))) { return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); } }
public static string stringify(object jsonObject) { using (var ms = new MemoryStream()) { new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } } }
上面这段代码是解析任何格式的JSON,返回一个类,当然前提是你首先新建一个类
下面来看看新建的类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace QAPITool { [Serializable] [DataContract] public class UserInfo { [DataMember] public string errcode; [DataMember] public string msg; [DataMember] public string ret; [DataMember] public UDataInfo data; } [Serializable] [DataContract] public class UDataInfo { [DataMember] public int hasnext;//0 月 1 无 [DataMember] public Infoclass[] info; } [Serializable] [DataContract] public class Infoclass { [DataMember] public string name; [DataMember] public string openid; [DataMember] public string nick; [DataMember] public string fansnum; [DataMember] public string idolnum; [DataMember] public int sex; [DataMember] public string isvip; [DataMember] public string isfans; [DataMember] public string isidol; } }
类的实例已经定义完成,最后我们只需要调用这个JSON,返回类即可:
UserInfo ui = JSON.parse<UserInfo>(addResult);
记住:addResult必须是JSON格式的才能解析