asp.net 反序列化解决办法

asp.net 反序列化
asp.net 反序列化解决办法

如上图所示json内容,我如何把数据转成我想的类,如下:

public class JsonInfo
{
    public string success { get; set; }
    public string errorCode { get; set; }
    public string subErrorCode { get; set; }
    public string errorDesc { get; set; }
    public string subErrorDesc { get; set; }
    public string requestMethod { get; set; }
    public string stocks { get; set; }
    public string total { get; set; }
}

public class StocksInfo
{
    public string qty { get; set; }
    public string del { get; set; }
}


------解决思路----------------------
改下类型就可以了
public StocksInfo[] stocks { get; set; }
public int total { get; set; }
------解决思路----------------------
以下内容应该符合你的答案:


string str="";  //json对象

//json转JavaScriptObject
JavaScriptObject jObject = JavaScriptConvert.DeserializeObject(str) as JavaScriptObject;

//获取json中key值为stocks的内容,转为JavaScriptArray
JavaScriptArray list = jObject["stocks"] as JavaScriptArray;

//自定义接口stocks内容的泛型StocksInfo
List<StocksInfo> infolist = new List<StocksInfo>();

//遍历stocks内容
foreach (JavaScriptObject item in list)
{
    //把JavaScriptObject转为自定义对象
    StocksInfom = (StocksInfo)JavaScriptConvert.DeserializeObject(JavaScriptConvert.SerializeObject(item), typeof(StocksInfo));

    //把对象添加到泛型集合中
    infolist.Add(m);
}

------解决思路----------------------
引用:
第一个属性就错了:

public class JsonInfo
{
    public bool success { get; set; }
    public string errorCode { get; set; }
    public string subErrorCode { get; set; }
    public string errorDesc { get; set; }
    public string subErrorDesc { get; set; }
    public string requestMethod { get; set; }
    public StocksInfo[] stocks { get; set; }
    public int total { get; set; }
}


在此基础上使用我以下方法

public class JsonInfo
{
    public bool success { get; set; }
    public string errorCode { get; set; }
    public string subErrorCode { get; set; }
    public string errorDesc { get; set; }
    public string subErrorDesc { get; set; }
    public string requestMethod { get; set; }
    public List<StocksInfo> stocks { get; set; }
    public int total { get; set; }
}

string str =""//json
JavaScriptObject jObject = JavaScriptConvert.DeserializeObject(str) as JavaScriptObject;
API_SelectNum ms = (API_SelectNum)JavaScriptConvert.DeserializeObject(JavaScriptConvert.SerializeObject(jObject), typeof(API_SelectNum));
List<API_SelectInfo> l = ms.stocks;
Response.Write(l.Count.ToString());
Response.Write(ms.total);