Deserializetion with StreamReader and JsonTextReader not working

Viewed 627

I am busy writing a deserialization method but the deserialized object is not filled with any values. I am testing the core of the method in a test class.

    [TestMethod]
    public void DeserializeObject_WithReader()
    {
        string json = "{\"objectName\":\"joe\",\"objectAge\":30,\"objectDimensionX\":148.25,\"objectDimensionY\":95.87}";

        using (StringReader reader = new StringReader(json))
        {
            using (JsonTextReader jsonReader = new JsonTextReader(reader))
            {
                JsonSerializer ser = JsonSerializer.CreateDefault();
                var t = ser.Deserialize<SerializedObjectTestClass>(jsonReader);
            }
        }
    }

Here is my test class I am trying to populate

public class SerializedObjectTestClass
{
    private string ObjectName { get; set; }
    private int ObjectAge { get; set; }
    private decimal ObjectDimensionX { get; set; }
    private decimal ObjectDimensionY { get; set; }
}
2 Answers

Newtonsoft Json.NET does not serialize/deserialize private properties by default, so you need either make them public, or mark with JsonPropertyAttribute:

public class SerializedObjectTestClass
{
    public string ObjectName { get; set; }
    ....
}

Or:

public class SerializedObjectTestClass
{
    [JsonProperty]
    private string ObjectName { get; set; }
    ....
}

You can deserialize the whole object at once:

SerializedObjectTestClass obj = JsonConvert.DeserializeObject<SerializedObjectTestClass>(json);

Next thing is that for newtonsoft properties must be public :

 public class SerializedObjectTestClass
 {
     public string ObjectName { get; set; }
     public int ObjectAge { get; set; }
     public decimal ObjectDimensionX { get; set; }
     public decimal ObjectDimensionY { get; set; }
}

You can also add attribute above property :

[JsonProperty]
    private string Property{ get; set; }
Related