Search code examples
windows-phone-7json.net

Json.Net JsonConvert not deserializing properly?


I'm using Json.Net to handle the deserialzing of the response of API calls from the Pipl.com API in my application, and it works fine but for some strange reason it won't deserialize a specific property of the JSON string that I feed to the JsonConvert.DeserializeObject method.

My class is this:

public class Source
{
    public string Dsname { get; set; }
    public bool IsSponsored { get; set; }

    public string Url { get; set; }
    public string Domain { get; set; }

    public uint ExternalID { get; set; }

    public Source()
    {

    }
}

and everything except the Dsname gets deserialized properly. The Json to be converted is like this:

"source": {                    
    "@is_sponsored": false,
    "@ds_name": "Personal Web Space -MySpace",
    "url": "http://www.foo.bar"
    "domain": "myspace.com"
}

Any idea how to go about this problem? Thank you in advance.


Solution

  • I added a wrapper class and specified the property name as attributes, like this:

    public class Source
    {
        [JsonProperty(PropertyName = "@ds_name")]
        public string Dsname { get; set; }
    
        [JsonProperty(PropertyName = "@is_sponsored")]
        public bool IsSponsored { get; set; }
    
        public string Url { get; set; }
    
        public string Domain { get; set; }
    
        public uint ExternalID { get; set; }
    }
    
    public class RootObject
    {
        public Source source { get; set; }
    }
    

    Then I was able to deserialize fine:

    var json = "{\"source\": { \"@is_sponsored\": true, \"@ds_name\": \"Personal Web Space -MySpace\", \"url\": \"http://www.foo.bar\", \"domain\": \"myspace.com\"}}";
    
    var des = JsonConvert.DeserializeObject<RootObject>(json);
    

    Note that I:
    - wrapped your sample in a curly braces to make it valid JSON
    - added a missing comma
    - changed the value of "@is_sponsored" to not be the default value to verify it is desearialized correctly.