C# 解析JSON实现类的实例
<p>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); }
}</p><p> 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());
}
}
}
}
</p>
[csharp]
[csharp]
<span style="font-size:24px; background-color:#ff6666">上面这段代码是解析任何格式的JSON,返回一个类,当然前提是你首先新建一个类</span>
[csharp]
<span style="font-size:24px"></span>
[csharp]
<span style="font-size:24px">下面来看看新建的类:</span>
[csharp]
<span style="font-size:24px"></span><pre class="csharp" name="code"><span style="font-size:12px">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 易做图;
[DataMember]
public string isvip;
[DataMember]
public string isfans;
[DataMember]
public string isidol;
}
}
</span></pre><br>
[csharp]
<span style="font-size:24px"></span>
[csharp]
<span style="font-size:24px">类的实例已经定义完成,最后我们只需要调用这个JSON,返回类即可:</span>
[csharp]
<span style="font-size:24px"> UserInfo ui = JSON.parse<UserInfo>(addResult);</span>
[csharp]
<span style="font-size:24px"><span style="color:#ff0000">记住:<span style="font-size:24px">addResult必须是JSON格式的才能解析</span></span></span>
补充:软件开发 , C# ,