1
votes

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.

2
Try changing your Dsname to DsName, naming conventions sometimes lead to problemsnkchandra

2 Answers

1
votes

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.

1
votes

Ok I realize, this is a pretty old thread. But I ran into a similar issue earlier and came across this thread.

In my case the class I was trying to se/deserialize had a List<ClassName> public property in it. Which serialized fine, but wont deserialize. I switched it to ClassName[] and the fixed the deserialization problem.

Hope it helps someone else who comes across this thread, or at least gives them something else to look for.