代码之家  ›  专栏  ›  技术社区  ›  Giox

在C语言中将动态JSON转换为泛型数组#

  •  0
  • Giox  · 技术社区  · 5 年前

    我有一个应用程序生成的以下JSON:

    [{
        "market": "Thondwe",
        "commodity": 51,
        "price": "240",
        "date": "2016-07-07T00:00:00.000Z",
        "month": "07",
        "year": "2016",
        "dataSource": "Government",
        "priceType": 15,
        "unit": 5,
        "metadata": [{
            "Gender": "Male",
            "BirthYear": "1975"
        }]
    }, {
        "market": "Thondwe",
        "commodity": 51,
        "price": "240",
        "date": "2016-07-07T00:00:00.000Z",
        "month": "07",
        "year": "2016",
        "dataSource": "Government",
        "priceType": 15,
        "unit": 5,
        "metadata": [{
            "Age": "67",
            "Sales": "1234",
            "City": "Somewhere"
        }]
    }]
    

    正如您所看到的,除了元数据中包含的内容之外,所有属性都是相同的,其中包含的对象总是不同的,并且是基于用户设置的内容构建的。

    我必须用C#解析这个JSON并转换成一个对象。

    直到今天我都忽略了 元数据 ,并且我使用了以下代码,这些代码工作得很好:

    using System;
    using System.Collections.Generic;
    
    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    
    public partial class JsonSchema
    {
        [JsonProperty("templateId")]
        [JsonConverter(typeof(ParseStringConverter))]
        public int TemplateId { get; set; }
    
        [JsonProperty("frequency")]
        [JsonConverter(typeof(ParseStringConverter))]
        public int DataCollectionFrequencyID { get; set; }
    
        [JsonProperty("dataSource")]
        public string DataSource { get; set; }
    
        [JsonProperty("dateFormat")]
        public string DateFormat { get; set; }
    
        [JsonProperty("currency")]
        [JsonConverter(typeof(ParseStringConverter))]
        public int CurrencyID { get; set; }
    
        [JsonProperty("priceType")]
        [JsonConverter(typeof(ParseStringConverter))]
        public int PriceType { get; set; }
    
        [JsonProperty("rowHeader")]
        [JsonConverter(typeof(ParseStringConverter))]
        public int RowHeader { get; set; }
    
        [JsonProperty("headerHash")]
        public string HeaderHash { get; set; }
    
        [JsonProperty("discardedRows")]
        public List<string> DiscardedRows { get; set; }
    
        [JsonProperty("lastUpdateDate")]
        public DateTime LastUpdateDate { get; set; }
    
        [JsonProperty("columns")]
        public List<Column> Columns { get; set; }
    }
    
    public partial class Column
    {
        [JsonProperty("market")]
        public string Market { get; set; }
    
        [JsonProperty("date")]
        public string Date { get; set; }
    
        [JsonProperty("commodity")]
        public string Commodity { get; set; }
    
        [JsonProperty("unit")]
        public string Unit { get; set; }
    
        [JsonProperty("price")]
        public string Price { get; set; }
    
        [JsonProperty("priceType")]
        public string PriceType { get; set; }
    
        [JsonProperty("dataSource")]
        public string DataSource { get; set; }
    }
    
    public partial class JsonSchema
    {
        public static JsonSchema FromJson(string json) => JsonConvert.DeserializeObject<JsonSchema>(json, DataModel.Converter.Settings);
    }
    
    public static class Serialize
    {
        public static string ToJson(this JsonSchema self) => JsonConvert.SerializeObject(self, DataModel.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(int) || t == typeof(int?);
    
        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);
            int l;
            if (int.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 = (int)untypedValue;
            serializer.Serialize(writer, value.ToString());
            return;
        }
    
        public static readonly ParseStringConverter Singleton = new ParseStringConverter();
    }
    

    现在的问题是,我还需要检索元数据属性中存储的对象,但如何映射它?

    0 回复  |  直到 5 年前