【问题标题】:Simple JsonConvert.DeserializeObject not assigning properties简单的 JsonConvert.DeserializeObject 不分配属性
【发布时间】:2015-03-16 22:59:33
【问题描述】:

这应该可行,而且非常基本。我的 json 字符串是(来自调试器):

json    "{\"companyId\":0,\"companyName\":\"Windward 3\",\"apiKey\":null,\"isEnabled\":false,\"isActive\":false,\"accruedRtusThisMonth\":0,\"billedRtusThisMonth\":0,\"overageChargesThisMonth\":0.0,\"pricingMode\":3,\"discount\":null,\"billingMode\":1,\"maxAdditionalMonthlyCharge\":123.0,\"billing\":{\"personId\":0,\"companyId\":0,\"isActive\":false,\"isAdmin\":false,\"isBilling\":false,\"firstName\":\"David\",\"lastName\":\"Thielen\",\"address1\":\"1 Main St.\",\"address2\":null,\"city\":\"Boulder\",\"state\":\"CO\",\"country\":\"USA\",\"postalCode\":\"80301\",\"phone\":\"123-456-7890\",\"email\":\"david@windward.net\",\"password\":\"tree\"},\"creditCard\":{\"cardNumber\":\"4111111111111111\",\"expiration\":\"2015-02-18T23:37:01.3135786Z\",\"cvv\":\"123\",\"useCardPerson\":false,\"cardPerson\":null},\"nextBaseBillingDate\":\"0001-01-01T00:00:00\",\"nextOverageBillingDate\":\"0001-01-01T00:00:00\",\"billingStatus\":0,\"billingErrorDate\":null,\"deactivateDate\":null,\"deleteDate\":null}"   string

我的代码如下:

CompanyWrapper companyWrapper = JsonConvert.DeserializeObject<CompanyWrapper>(json,
                                                new JsonSerializerSettings());

CompanyWrapper 类是:

public class CompanyWrapper
{
    /// <summary>
    /// For the JSON population.
    /// </summary>
    public CompanyWrapper()
    {
    }

    /// <summary>
    /// For unit tests
    /// </summary>
    public CompanyWrapper(string companyName, PricingPlan.PRICING_MODE pricingMode, Company.BILLING_MODE billingMode, decimal maxAdditionalMonthlyCharge, PersonWrapper billing, CreditCardWrapper creditCard)
    {
        this.companyName = companyName;
        this.pricingMode = pricingMode;
        this.billingMode = billingMode;
        this.maxAdditionalMonthlyCharge = maxAdditionalMonthlyCharge;
        this.billing = billing;
        this.creditCard = creditCard;
    }

    /// <summary>
    /// The primary key. This is auto-generated in the database.
    /// </summary>
    public int companyId { get; private set; }

    /// <summary>
    /// The company name. This cannot be changed.
    /// </summary>
    public string companyName { get; private set; }
...
}

返回 companyWrapper.companyName == null。那应该分配。我错过了什么?

谢谢 - 戴夫

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    您需要公开属性设置器。

    【讨论】:

    • Aargh - json.NET 不会使用反射来设置私有的? Dapper 做到了这一点,这真的很好,因为我们可以为所有代码保留私有。无论如何,就是这样 - 现在一切正常。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多