在C#中反序列化为现有的类实例

时间:2018-03-26 00:51:20

标签: c# json.net deserialization json-deserialization

这可以应用于几个问题,其中列表包含有限数量的项目,如城市,货币,语言等列表。

我正在尝试找到一种方法将类序列化为其Id,然后反序列化回其完整描述。例如,如果我们有这样的城市结构:

public struct City
{
    public string Name;
    public Country Country;
}

[JsonObject(MemberSerialization.OptIn)]
public class Country
{
    public Country(string code, string name) { Code = code; Name = name; }
    [JsonProperty]
    public string Code;
    public string Name;
}

public class Countries
{
    public static List<Country> All = new List<Country>()
    {
        new Country("US", "United States"),
        new Country("GB", "United Kingdom"),
        new Country("FR", "France"),
        new Country("ES", "Spain"),
    };
}

我不介意国家序列化为{&#34;代码&#34;:&#34; ES&#34;}或简单地&#34; ES&#34;,但我希望它被反序列化为Countries.All中的现有国家实例

我怎么能得到这种行为?

2 个答案:

答案 0 :(得分:2)

您有两种解决方案:

  • 使用枚举和扩展功能,这将简化验证过程以及枚举特别限制值
  • 使用自定义JsonConverters使用ids / code转换您的JSON数据,这将允许您自定义它们被序列化为JSON的方式

我很快就会有例子,我需要先输入em。 编辑:示例已完成

在这两种情况下
在这两个示例中,我使用JsonConvertAttribute来设置在序列化或反序列化对象时应使用哪个转换器。此参数告诉json.net库默认情况下序列化对象/参数时要使用的类/转换器。

如果您只需要在特定时刻进行序列化,则必须选择2种不同的方案:

  • 序列化数组/列表时
    • 将JsonPropertyAttribute添加到属性中,并将ItemConverterType设置为转换器的类型。
  • 序列化其他任何内容时
    • 将JsonConvertAttribute添加到属性中,并在构造函数中传递JSON转换器。

将国家/地区保留为对象/结构
在我看来,这个选项是2个解决方案中最灵活和最实用的选项,因为它允许更改需求和减少异常抛出。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyApplication
{

    public struct City
    {
        public string Name;
        // you could also set a converter for this field specifically if you only need for specific fields but also
        // still want it to display as a normal json object when you serialise the object.
        // [JsonConverter(typeof(CountryConverter))]
        public Country Country;
    }

    // Setting a json converter attribute allows json.net to understand that an object by default
    // will be serialised and deserialised using the specified converter.
    [JsonConverter(typeof(CountryConverter))]
    public class Country
    {
        public Country(string code)
        {
            switch (code)
            {
                case "US": Name = "United-States"; break;
                case "GB": Name = "United Kingdom"; break;
                case "FR": Name = "France"; break;
                case "ES": Name = "Spain"; break;
                case "CA": Name = "Canada"; break;
            }
        }
        public string Code { get; set; }
        public string Name { get; set; }
    }


    public class CountryConverter : JsonConverter<Country>
    {
        // Assuming that the countries are serialised using the code
        public override Country ReadJson(JsonReader reader, Type objectType, Country existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if(reader.Value == null && reader.ValueType == typeof(string))
            {
                return null;
            }

            string code = (string) reader.Value;
            code = code.ToUpperInvariant(); // Because reducing error points is usually a good thing

            return new Country(code);

        }

        public override void WriteJson(JsonWriter writer, Country value, JsonSerializer serializer)
        {
            //Writes the code as the value for the object
            writer.WriteValue(value.Code);
        }
    }
}

将国家/地区更改为枚举
使用枚举可能很棒,因为它允许您拥有一组不变的值,而不必一遍又一遍地创建新对象。但它会使你的转换逻辑变得更复杂。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyApplication
{

    public struct City
    {
        public string Name;
        public Country Country;
    }

    // Using the full name as it makes it easier to work with and also because you'd need a json converter
    // if you want a string and not the number/index of the country when you serialise the data
    [JsonConverter(typeof(CountryConverter))]
    public enum Country
    {
        UnitedStates,
        UnitedKingdom,
        France,
        Spain,
        Canada
    }

    // this class only exists for you to add extentions to this enums.
    // In short extentions are a type of methods added to other classes that act
    // as if they were part of outher classes. usually this means that the first parameter
    // is prefixed by this.
    public static class CountryExtentions
    {
        public static string GetCode(this Country country)
        {
            switch (country)
            {
                case Country.UnitedStates: return "US";
                case Country.UnitedKingdom: return "GB";
                case Country.France: return "FR";
                case Country.Spain: return "SP";
                case Country.Canada: return "CA";
                default: throw new InvalidOperationException($"This country has no code {country.ToString()}");
            }
        }
    }
    public class CountryConverter : JsonConverter<Country>
    {
        // Assuming that the countries are serialised using the code
        public override Country ReadJson(JsonReader reader, Type objectType, Country existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            // make sure you can convert the thing into a string
            if (reader.Value == null && reader.ValueType == typeof(string))
            {
                throw new InvalidOperationException($"The data type passed {reader.ValueType.Name} isn't convertible. The data type musts be a string.");
            }

            // get the value
            string code = (string)reader.Value;
            code = code.ToUpperInvariant(); // Because reducing error points is usually a good thing

            // cycle through the enum values to compare them to the code
            foreach (Country country in Enum.GetValues(typeof(Country)))
            {
                // if the code matches
                if (country.GetCode() == code)
                {
                    // return the country enum
                    return country;
                }
            }
            // if no match is found, the code is invlalid
            throw new InvalidCastException("The provided code could not be converted.");

        }

        public override void WriteJson(JsonWriter writer, Country value, JsonSerializer serializer)
        {
            //Writes the code as the value for the object
            writer.WriteValue(value.GetCode());
        }
    }
}

答案 1 :(得分:1)

我建议使用JsonConverter,如此:

public class CountryConverter : JsonConverter
{
    public override bool CanRead { get { return true; } }
    public override bool CanWrite { get { return false; } }

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = JObject.Load(reader);
        var code = obj.GetValue("code", StringComparison.OrdinalIgnoreCase)?.Value<string>();
        if (code != null)
        {
            return Countries.All.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase));
        }
        return null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

它不负责序列化对象,只对其进行反序列化。要反序列化它们,它会读取&#34;代码&#34;字段,然后从Countries.All列表返回第一个匹配的国家/地区。使用字典可能是最好的(更有效率)。

要使用此功能,只需装饰您的国家/地区类:

[JsonConverter(typeof(CountryConverter))]
public class Country