【问题标题】:Getting null values when converting json to list of c# objects将 json 转换为 c# 对象列表时获取空值
【发布时间】:2018-12-06 20:27:23
【问题描述】:

这是json:

[
    {
        "FirstName": "bob",
        "LastName": "ob",
        "Country": "vxv",
        "CityOrTown": "aaaaa",
        "Line1": "3EF1A60C-4en St.dsadsa",
        "PostalCode": "91106",
        "BirthDay": "07",
        "BirthMonth": "06",
        "BirthYear": "2000"
    },
    {
        "FirstName": "bbb",
        "LastName": "bbb",
        "Country": "bbb",
        "CityOrTown": "bbb",
        "Line1": "bbb",
        "PostalCode": "bbb",
        "BirthDay": "06",
        "BirthMonth": "06",
        "BirthYear": "2000"
    }
]

这是我想将此 json 转换为的对象:

namespace Stripe
{
    public class StripeAccountAdditionalOwner : INestedOptions
    {
        public StripeAccountAdditionalOwner();

        [JsonProperty("[address][city]")]
        public string CityOrTown { get; set; }

        [JsonProperty("[address][country]")]
        public string Country { get; set; }

        [JsonProperty("[address][line1]")]
        public string Line1 { get; set; }

        [JsonProperty("[address][line2]")]
        public string Line2 { get; set; }

        [JsonProperty("[address][postal_code]")]
        public string PostalCode { get; set; }

        [JsonProperty("[address][state]")]
        public string State { get; set; }

        [JsonProperty("[dob][day]")]
        public int? BirthDay { get; set; }

        [JsonProperty("[dob][month]")]
        public int? BirthMonth { get; set; }

        [JsonProperty("[dob][year]")]
        public int? BirthYear { get; set; }

        [JsonProperty("[first_name]")]
        public string FirstName { get; set; }

        [JsonProperty("[last_name]")]
        public string LastName { get; set; }

        [JsonProperty("verification[document]")]
        public string VerificationDocument { get; set; }
    }
}

这是我在控制器中使用的代码:

List<StripeAccountAdditionalOwner> AdditionalOwners = JsonConvert.DeserializeObject<List<StripeAccountAdditionalOwner>>(requestData.CompanyOwners);

requestData.CompanyOwners 是对象的 json 数组。

注意:它没有给我任何错误。没有丢失的引用,它完美地通过了这行代码,但是所有值都保持为空。 在此先感谢各位,非常感谢。

【问题讨论】:

  • 查找 JsonProperty 属性 (newtonsoft.com/json/help/html/…) 的文档。我认为您误解了该属性的真正作用。
  • 是的,您的[JsonProperty()] 属性毫无意义。仅当 json 键与您的属性名称不同时才使用 JsonProperty。序列化程序不区分大小写,因此如果您在 JSON 中的属性是 someKey 并且您的 C# 属性是 SomeKey 就可以了
  • @user10001850 只需从所有属性中删除[JsonProperty] 属性除非 C# 中的名称与 JSON 中的名称不同。链接的文档 elgonzo 将解释所有这些
  • 您显示的 json 不是 Stripe 返回的,您问题中的类在 Stripe.NET 内部使用(使用自定义 JsonConverter)将其 json 反序列化为强类型对象。目前还不清楚根本您要达到什么目的:您想反序列化 Stripe 响应还是尝试创建不同的模型(用于不同的目的)?
  • 然后创建另一个类,该类符合your json。您复制/粘贴的内容不适用于您的情况。

标签: c# arrays json c#-4.0 stripe-payments


【解决方案1】:

使用 [https://app.quicktype.io/#l=cs&r=json2csharp][1] 能够为问题中的 JSON 生成以下类

using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class Welcome
{
    [JsonProperty("FirstName")]
    public string FirstName { get; set; }

    [JsonProperty("LastName")]
    public string LastName { get; set; }

    [JsonProperty("Country")]
    public string Country { get; set; }

    [JsonProperty("CityOrTown")]
    public string CityOrTown { get; set; }

    [JsonProperty("Line1")]
    public string Line1 { get; set; }

    [JsonProperty("PostalCode")]
    public string PostalCode { get; set; }

    [JsonProperty("BirthDay")]
    public string BirthDay { get; set; }

    [JsonProperty("BirthMonth")]
    public string BirthMonth { get; set; }

    [JsonProperty("BirthYear")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long BirthYear { get; set; }
}

public partial class Welcome
{
    public static Welcome[] FromJson(string json) => JsonConvert.DeserializeObject<Welcome[]>(json, QuickType.Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this Welcome[] self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters = {
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
    };
}

internal class ParseStringConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        long l;
        if (Int64.TryParse(value, out l))
        {
            return l;
        }
        throw new Exception("Cannot unmarshal type long");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (long)untypedValue;
        serializer.Serialize(writer, value.ToString());
        return;
    }

    public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}

【讨论】:

  • 什么是 ParseStringConverter
  • Christian,它是一个 JSONConverter,用于序列化和反序列化 JSON 字符串从对象到对象
【解决方案2】:

使用它作为你的模型类

    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class JsonModel
    {
        [JsonProperty("FirstName")]
        public string FirstName { get; set; }

        [JsonProperty("LastName")]
        public string LastName { get; set; }

        [JsonProperty("Country")]
        public string Country { get; set; }

        [JsonProperty("CityOrTown")]
        public string CityOrTown { get; set; }

        [JsonProperty("Line1")]
        public string Line1 { get; set; }

        [JsonProperty("PostalCode")]
        public string PostalCode { get; set; }

        [JsonProperty("BirthDay")]
        public string BirthDay { get; set; }

        [JsonProperty("BirthMonth")]
        public string BirthMonth { get; set; }

        [JsonProperty("BirthYear")]

        public string BirthYear { get; set; }
    }

然后在您的主课中执行此操作

            var data = JsonConvert.DeserializeObject<JsonModel>(jsonstring);
            var country = data.Country;
            var birthday = data.BirthDay;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多