.

Deserializing Json

[TestMethod]
public void Deserialize_Concrete()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";
    var serializer = new JavaScriptSerializer();
    var qwer = serializer.Deserialize<List<FeedbackReport>>(json);
}

[Serializable]
public class FeedbackReport
{
    public List<Feed> Feeds;
}

[Serializable]
public class Feed
{
    public float BuyRate;
    public float Change;
    public float DailyHigh;
    public float DailyLow;
    public string InstrumentID;
    public string InstrumentName;
    public float SellRate;
}

[TestMethod]
public void Deserialize_Dynamically()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";

    var serializer = new JavaScriptSerializer();  //System.Web.Script.Serialization.JavaScriptSerializer

    //might perhaps need the following line - not always
    //serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

    var DeserializedObj = serializer.Deserialize(json, typeof(object));
}

One Response to this post.

  1. Posted by Gladys on 31.08.13 at 11:07 am

    First of all, I am using a Dictionary, not an IDictionary. Apart form that, you have it exactly right. You can’t pass an (I)Dictionary to a web srcviee as a parameter. The SOAP Formatter simply simply won’t buy that – but the ASP.NET JSON Formatter will! It works exactly as I described. If you try accessing that web srcviee in the ‘normal’ way, it will not work. Heck, you can’t even get a decent WSDL out of it ;-) . But as a JSON srcviee, it works. Don’t ask me how, thank the anonymous Microsoft programmer

What's your thoughts on this?

*

Protected by WP Anti Spam