Using Anonymous types to deserialize JSON data



C# 2.0

The JSON text that I am trying to parse is this:



class HelloWorldResponse
    public string Text { get; set; }
    public string Status { get; set; }



C# 3.0



Here is the method that converts object to the anonymous type:

public static class TypeExtension
        return (T)o;


Then, I can just write the code like this:




C# 4.0






Comments (8)

  1. Jim says:

    The code above (C# version 4.0) doesn't work.

    The anonymous class doesn't have a default constructor.

    This might be something new in release version of C#. The javascript serializer also takes a string now, not a reader.

  2. Jake says:

    The 3.0 version doesn't work either. Could you put some source files of working examples here for reference?

  3. What is the error you are seeing with the C# 3.0 version?

  4. Alex Dan says:

    The .NET 4.0 method is awesome and makes my life much easier. One note: in your examples, it's not clear which class the "js" in js.Deserialize() refers to.

  5. Alex Dan says:


  6. Hey Alex.

    The js refers to the JSON Deserializer I used –…/ProjectReleases.aspx.


  7. Synn says:

    string JSONText = "{Text:"Hello World!!", Status:"Ok"}";


    var y = JavaScriptConvert.DeserializeObject(JSONText, helloResponse.GetType()).ToType(helloResponse);

    //now you can access properties with  y.Test and  y.Statu

  8. Chris says:

    Thanks, this was the most helpful explanation of JSON deserialization I've come across. I'm mainly interested in how to deserialize custom classes and arrays. Here's one of my JSON service responses:


      "ResultPageNumber":"String content",

      "ResultPageTotal":"String content",


         "Group":"String content",

         "Size":"String content",

         "Subject":"String content",



    In SOAP this is easy. With WCF REST I assumed it would also be easy. The only reason to use WCF REST over SOAP in C# is if you're looking at supporting other client types that have poor support for SOAP. (like say Android) I'm not explicitly supporting Android, as I want to implemented a couple of useful clients for the service, but I'm a little disheartened on the client-side JSON support available within .Net. I can parse it all out myself, but this is something that .Net could magically transform for us. (I mean SOAP support is top notch on all sides) Maybe I'm completely missing the boat. I apologize if I am, but any help would be welcome. Thanks.

Skip to main content