在C#

时间:2019-05-17 20:07:53

标签: c# json json.net

我具有应用程序生成的以下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 个答案:

没有答案