Newtonsoft.Json DeserializedObject错误的属性值

时间:2018-06-07 16:22:23

标签: json.net

使用此处找到的示例。 https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

deserializedProduct不会以正确的值结束。有人可以指出我所缺少的吗?

using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product product = new Product();

            product.Name = "Apple";
            product.ExpiryDate = new DateTime(2008, 12, 28);
            product.Price = 3.99M;
            product.Sizes = new string[] { "Small", "Medium", "Large" };

            string output = JsonConvert.SerializeObject(product);
            //{
            //  "Name": "Apple",
            //  "ExpiryDate": "2008-12-28T00:00:00",
            //  "Price": 3.99,
            //  "Sizes": [
            //    "Small",
            //    "Medium",
            //    "Large"
            //  ]
            //}

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
        }
    }

    class Product
    {
        public string Name { get; internal set; }
        public DateTime ExpiryDate { get; internal set; }
        public decimal Price { get; internal set; }
        public string[] Sizes { get; internal set; }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

在反序列化时,属性需要公共getter和setter才能设置值

class Product
{
    public string Name { get; set; }
    public DateTime ExpiryDate { get; set; }
    public decimal Price { get; set; }
    public string[] Sizes { get; set; }
}