将JSON对象反序列化为嵌套的C#对象 [英] Deserialize JSON object into nested C# object

查看:126
本文介绍了将JSON对象反序列化为嵌套的C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我想我应该提到我无法控制JSON,而且我知道通常我的C#对象应该与JSON匹配.我的问题不是为什么不反序列化?".我知道为什么不是这样.我在问是否有一种方法可以按照我的要求反序列化JSON.

Edit: I guess I should mention that I do not have control over the JSON and I know that typically my C# object should match the JSON. My question wasn't "why isn't this deserializing?". I know why it's not. I am asking if there is a way to deserialize the JSON the way that I am asking.

我正在使用Newtonsoft.Json.

I am using Newtonsoft.Json.

我有一个包含1个对象的JSON字符串.我需要将该对象反序列化为带有嵌套对象的C#对象.

I have a JSON string containing 1 object. I need to deserialize that object into a C# object with a nested object.

所以可以说我的JSON看起来像这样.

So lets say my JSON looks like this.

{
    "id": 123,
    "userName": "fflintstone",
    "address": "345 Cave Stone Road",
    "address2": "",
    "city": "Bedrock",
    "state": "AZ",
    "zip": "",   
}

这是我的C#对象

public class Customer
{
    public long Id { get; set; }

    public string UserName { get; set; }

    public AddressModel Address { get; set; }
}

AddressModel地址属性是一个嵌套对象.该对象包含实际的地址属性.因此,我需要反序列化JSON对象,以便将id和userName添加到Customer对象,然后将地址字段添加到嵌套的Address对象.

The AddressModel Address property is a nested object. That object contains the actual address properties. So I need to deserialze my JSON object so that id and userName are added to the Customer object and then the address fields are added to the nested Address object.

我无法找到newtonsoft内置的方法来实现此目的.有什么想法吗?

I haven't been able to find a way that is built into newtonsoft to accomplish this. Any ideas?

推荐答案

您可以使用自定义JsonConverter进行此操作.

You can do this using a custom JsonConverter.

public class CustomerJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is Customer customer)
        {
            var token = new JObject
            {
                ["id"] = customer.Id,
                ["userName"] = customer.UserName,
                ["address"] = customer.Address.Address,
                ["address2"] = customer.Address.Address2,
                ["city"] = customer.Address.City,
                ["state"] = customer.Address.State,
                ["zip"] = customer.Address.ZIP
            };

            token.WriteTo(writer);
        }
        else
        {
            throw new InvalidOperationException();
        }

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = JToken.ReadFrom(reader);

        if (obj.Type != JTokenType.Object)
        {
            return null;
        }

        return new Customer
        {
            Id = (long) obj["id"],
            UserName = (string) obj["userName"],
            Address = obj.ToObject<AddressModel>()
        };
    }

    public override bool CanRead => true;

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Customer);
    }
}

Customer 类上带有 JsonConverterAttribute .

[JsonConverter(typeof(CustomerJsonConverter))]
public class Customer
{
    public long Id { get; set; }

    public string UserName { get; set; }

    public AddressModel Address { get; set; }
}

public class AddressModel
{
    public string Address { get; set; }

    public string Address2 { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string ZIP { get; set; }
}

并这样利用:

var customer = JsonConvert.DeserializeObject<Customer>(customerJson);

或者,您可以简单地使用一个中间映射模型.

alternatively, you could simply have an intermediate mapping model.

public class CustomerFlattened
{
    public long Id { get; set; }

    public string UserName { get; set; }

    public string Address { get; set; }

    public string Address2 { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string ZIP { get; set; }

    public Customer ToCustomer()
    {
        return new Customer
        {
            Id = Id,
            UserName = UserName,
            Address = new AddressModel
            {
                Address = Address,
                Address2 = Address2,
                City = City,
                State = State,
                ZIP = ZIP
            }
        };
    }

    public static CustomerFlattened FromCustomer(Customer customer)
    {
        return new CustomerFlattened
        {
            Id = customer.Id,
            UserName = customer.UserName,
            Address = customer.Address.Address,
            Address2 = customer.Address.Address2,
            City = customer.Address.City,
            State = customer.Address.State,
            ZIP = customer.Address.ZIP
        };
    }
}

并这样利用:

var customer =
    JsonConvert.Deserialize<CustomerFlattened>(
        jsonOriginal
    )
    .ToCustomer();

var customerFlattened = CustomerFlattened.FromCustomer(customer);

var jsonConverted = JsonConvert.Serialize(customerFlattened );

这篇关于将JSON对象反序列化为嵌套的C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆