Narayanan
Narayanan

Reputation: 115

Deserialize JSON attribute to class

For the most part my JSON deserialization seems to work fine except for the last attribute that I added. I have the following JSON string. If I keep my class property type as string for the attribute httpVerb, the deserialization works just fine. But if I keep class property type as System.Net.HttpMethod for the attribute httpVerb then the deserialization is failing. I really hate to create another enum as the HTTP verbs are already defined in the HttpMethod class.

Can someone help?

{
    "httpTest": {
        "ignoreCertificateErrors": false, 
        "successHTTPStatusCodes": [ 200 ], 
        "httpVerb": "GET"
    }
}

public class HttpTest
{
    public bool ignoreCertificateErrors { get; set; }
    public List<HttpStatusCode> successHTTPStatusCodes { get; set; }
    public HttpMethod httpVerb { get; set; }
}

public class RootObject
{
    public HttpTest httpTest { get; set; }
}

Upvotes: 2

Views: 343

Answers (1)

David L
David L

Reputation: 33833

You have to deserialize your json verb as a string. That said, you can return the corresponding HttpMethod instance to preserve your strong typing with the addition of another property.

public class HttpTest
{
    public bool ignoreCertificateErrors { get; set; }
    public List<HttpStatusCode> successHTTPStatusCodes { get; set; }
    public string httpVerb { get; set; }
    public HttpMethod HttpMethodInstance { 
        get { return new HttpMethod(httpVerb); }
    }
}

If your verb is a valid verb, you can use it to instantiate a new instance of HttpMethod

Upvotes: 3

Related Questions