简体   繁体   中英

How to parse data from Web Service in ASP.net

I am retrieving a String from SOAP service to asp.net. I am not able to understand how to parse this string and into what variable type? Array? collection? Object?. The retrieved string looks like this:

<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>

What you are retrieving is a XML with JSON data in it.

If you extract the JSON string from it then there are a couple of ways you can use this return string. You could create a custom class for it with all the fields that are mentioned in the JSON structure (Category, CategoryID, ProductCount, DisplayName) and then serialize the string to objects of your custom class type.

This would look like:

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

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

You can also use the new dynamic keyword in C#4 like this:

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

Then you won't have to define a class for your objects and you can access the items trough d.Category for example and at runtime .NET will check if the property is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM