greatbear302 greatbear302 - 1 month ago 16
C# Question

What am I doing wrong with JSON.NET's JsonConvert

json string

{
"success": true,
"challenge_ts": "2016-11-03T17:30:00Z",
"hostname": "mydomain.com"
}


class

internal class reCaptchaResponse
{
internal bool success { get; set; }
internal DateTime challenge_ts { get; set; } // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
internal string hostname { get; set; } // the hostname of the site where the reCAPTCHA was solved
internal string[] error_codes { get; set; } // optional
}


attempt to serialize

reCaptchaResponse responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<reCaptchaResponse>(jsonResult);


attempt fails like...

Newtonsoft.Json.JsonConvert.SerializeObject(responseObject)
returns
{}

L.B L.B
Answer

Json.Net, by default, only serializes/deserialzes public fileds and properties, but you can also do it without changing access modifiers from internal to public.

Just use JsonProperty attribute

internal class reCaptchaResponse
{
    [JsonProperty]
    internal bool success { get; set; }
    [JsonProperty]
    internal DateTime challenge_ts { get; set; }  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
    [JsonProperty]
    internal string hostname { get; set; }        // the hostname of the site where the reCAPTCHA was solved
    [JsonProperty]
    internal string[] error_codes { get; set; }   // optional
}

(Without modifing the original class) You can even use ContractResolver to select which properties/fields should be used in serialization process