如何从ASP.net中的Web Service解析数据

时间:2011-11-26 10:07:40

标签: asp.net xml json asp.net-mvc-3

我正在从SOAP服务检索String到asp.net。 我无法理解如何解析这个字符串并进入什么变量类型?阵列?采集?宾语?。检索到的字符串如下所示:

<string>
[{"Category":"Mobile Common Needs","CategoryID":"{6039207E61CB}","ProductCount":8,"DisplayName":"Mobile Common Needs"},{"Category":"A Vitamins","CategoryID":"{DB3AD2CE2EAD}","ProductCount":4,"DisplayName":"A Vitamins"},{"Category":"B Complex","CategoryID":"{82133AF08331}","ProductCount":7,"DisplayName":"B Complex"},{"Category":"B Vitamins","CategoryID":"{4BE6939D8F7E}","ProductCount":9,"DisplayName":"B Vitamins"},{"Category":"C Vitamins","CategoryID":"{29D6977A7DCB}","ProductCount":9,"DisplayName":"C Vitamins"},{"Category":"D Vitamins","CategoryID":"{FF8A7E14F1E5}","ProductCount":7,"DisplayName":"D Vitamins"},{"Category":"E Vitamins","CategoryID":"{459AEF26893A}","ProductCount":6,"DisplayName":"E Vitamins"},{"Category":"Health Solutions","CategoryID":"{44C28190872F}","ProductCount":10,"DisplayName":"Health Solutions"},{"Category":"Herb Supplements","CategoryID":"{C24C77EC05EF}","ProductCount":15,"DisplayName":"Herb Supplements"},{"Category":"Minerals","CategoryID":"{A9153D05AAEE}","ProductCount":13,"DisplayName":"Minerals"},{"Category":"Multivitamins","CategoryID":"{79E8951CAC06}","ProductCount":13,"DisplayName":"Multivitamins"},{"Category":"Sleep Aid","CategoryID":"{1D2F16A124BB}","ProductCount":1,"DisplayName":"Sleep Aid"},{"Category":"Supplements","CategoryID":"{9BE59D6B9B23}","ProductCount":22,"DisplayName":"Supplements"},{"Category":"Vitamin Packs","CategoryID":"{9FE0A91C0AA3}","ProductCount":5,"DisplayName":"Vitamin Packs"}]
</string>

1 个答案:

答案 0 :(得分:5)

您要检索的是包含JSON数据的XML。

如果从中提取JSON字符串,则有几种方法可以使用此返回字符串。您可以使用JSON结构中提到的所有字段(Category,CategoryID,ProductCount,DisplayName)为其创建自定义类,然后将字符串序列化为自定义类类型的对象。

这看起来像是:

DataContractJsonSerializer serializer = 
    new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType = (YourObjectType)serializer.ReadObject(str);

您也可以在C#4中使用新的动态关键字,如下所示:

using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d=jss.Deserialize<dynamic>(str);

然后你不必为你的对象定义一个类,你可以通过d.Category访问这些项目,在运行时.NET会检查属性是否可用。