本文介绍了将JSON解析为C#对象-动态获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(跳到一句tl; dr的粗体部分)

(Skip to bolded part for one-sentence tl;dr:)

我下面有JSON对象.在查看它之前,请注意:

I have the JSON object below. Before looking at it, note that:

  • BTC_AMP这样的货币对列表永远存在,为便于示例,我将其剪掉
  • BTC_AMP似乎是一个包含一些字段的命名对象.

  • The list of currency pairs like BTC_AMP goes on forever, I cut it off for the sake of example
  • BTC_AMP appears to be a NAMED OBJECT containing some fields.

{
"BTC_AMP": {
    "asks": [
        [
            "0.00007400",
            5
        ]
    ],
    "bids": [
        [
            "0.00007359",
            163.59313969
        ]
    ],
    "isFrozen": "0",
    "seq": 38044678
},
"BTC_ARDR": {
    "asks": [
        [
            "0.00003933",
            7160.61031389
        ]
    ],
    "bids": [
        [
            "0.00003912",
            1091.21852308
        ]
    ],
    "isFrozen": "0",
    "seq": 16804479
},
}

我可以使用 Json.NET 映射对象,如.我的问题是,在我看来,我需要创建一个对象并为一千种货币对预定义属性名称,例如BTC_AMPBTC_ARDR等.

I can map the object just fine using Json.NET as described here. My problem is that it seems to me that I need to create an object and predefine property names such as BTC_AMP, BTC_ARDR, and so on for a thousand currency pairs.

您可能会看到我要使用的对象... 如何在不预先创建每个对名的情况下映射该对象?

You can probably see where I am going with this...how do I map this object without pre-creating every single pair name?

希望我在这里缺少明显的东西.

Hoping I am missing something obvious here.

代码看起来像这样,我不想做什么:

Code looks like this, what I DON'T want to do:

public class PoloniexPriceVolume
{
    public string Price { get; set; }
    public double Volume { get; set; }
}

public class PoloniexPairInfo
{
    public PoloniexPriceVolume Asks { get; set; }
    public PoloniexPriceVolume Bids { get; set; }
    public bool IsFrozen { get; set; }
    public int Seq { get; set; }

}

public class PoloniexOrderBook
{
    public PoloniexPairInfo BTC_AMP { get; set; }
    //One thousand and one Arabian currency pairs here
}


编辑2 ...如果我在某处有货币对列表,是否可以至少动态创建一个对象/一个对象的属性?似乎没有手工编写那么荒谬.


Edit 2...can I at least dynamically create an object / an object's properties if I have a list of currency pairs somewhere? Seems less ridiculous than writing it by hand.

推荐答案

您在这里遇到几个问题:

You have several issues here:

  • 您的根对象具有大量可变的属性,其值对应于固定数据类型PoloniexPairInfo.由于您不想创建对所有这些属性进行硬编码的根类型,因此可以反序列化为Dictionary<string, PoloniexPairInfo>,如创建强类型json对象中ID为名称的c#对象.

  • Your root object has a large, variable number of properties whose values correspond to a fixed data type PoloniexPairInfo. Since you don't want to create a root type that hardcodes all these properties, you can deserialize to a Dictionary<string, PoloniexPairInfo> as shown in Create a strongly typed c# object from json object with ID as the name.

BidAsk属性在JSON中表示为不同类型的值数组的数组:

The Bid and Ask properties are represented in JSON as an array of arrays of values of different types:

[
  [
    "0.00007359",
    163.59313969
  ]
]

您想通过将特定数组索引处的值绑定到特定c#属性来将内部数组映射到固定POCO PoloniexPriceVolume.您可以使用 C#JSON.NET中的ObjectToArrayConverter<PoloniexPriceVolume>来做到这一点-反序列化使用异常数据结构的响应.

You would like to map the inner arrays to a fixed POCO PoloniexPriceVolume by binding values at specific array indices to specific c# properties. You can do this using ObjectToArrayConverter<PoloniexPriceVolume> from C# JSON.NET - Deserialize response that uses an unusual data structure.

最后,JSON值"isFrozen"具有字符串值"0",但是您希望将其映射到boolpublic bool IsFrozen { get; set; }.您可以通过从使用Json.Net将int转换为bool来修改BoolConverter.

Finally, the JSON value "isFrozen" has a string value "0" but you would like to map it to a bool value public bool IsFrozen { get; set; }. You can do this by adapting BoolConverter from Convert an int to bool with Json.Net.

将所有这些放在一起,您可以使用以下模型和转换器反序列化JSON:

Putting all this together, your can deserialize your JSON with the following models and converters:

[JsonConverter(typeof(ObjectToArrayConverter<PoloniexPriceVolume>))]
public class PoloniexPriceVolume
{
    [JsonProperty(Order = 1)]
    public string Price { get; set; }
    [JsonProperty(Order = 2)]
    public double Volume { get; set; }
}

public class PoloniexPairInfo
{
    public List<PoloniexPriceVolume> Asks { get; set; }
    public List<PoloniexPriceVolume> Bids { get; set; }
    [JsonConverter(typeof(BoolConverter))]
    public bool IsFrozen { get; set; }
    public int Seq { get; set; }
}

public class ObjectToArrayConverter<T> : JsonConverter
{
    //https://stackoverflow.com/a/39462464/3744182
    public override bool CanConvert(Type objectType)
    {
        return typeof(T) == objectType;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectType = value.GetType();
        var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));
        writer.WriteStartArray();
        foreach (var property in SerializableProperties(contract))
        {
            var propertyValue = property.ValueProvider.GetValue(value);
            if (property.Converter != null && property.Converter.CanWrite)
                property.Converter.WriteJson(writer, propertyValue, serializer);
            else
                serializer.Serialize(writer, propertyValue);
        }
        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));

        if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType != JsonToken.StartArray)
            throw new JsonSerializationException(string.Format("token {0} was not JsonToken.StartArray", reader.TokenType));

        // Not implemented: JsonObjectContract.CreatorParameters, serialization callbacks,
        existingValue = existingValue ?? contract.DefaultCreator();

        using (var enumerator = SerializableProperties(contract).GetEnumerator())
        {
            while (true)
            {
                switch (reader.ReadToContentAndAssert().TokenType)
                {
                    case JsonToken.EndArray:
                        return existingValue;

                    default:
                        if (!enumerator.MoveNext())
                        {
                            reader.Skip();
                            break;
                        }
                        var property = enumerator.Current;
                        object propertyValue;
                        // TODO:
                        // https://www.newtonsoft.com/json/help/html/Properties_T_Newtonsoft_Json_Serialization_JsonProperty.htm
                        // JsonProperty.ItemConverter, ItemIsReference, ItemReferenceLoopHandling, ItemTypeNameHandling, DefaultValue, DefaultValueHandling, ReferenceLoopHandling, Required, TypeNameHandling, ...
                        if (property.Converter != null && property.Converter.CanRead)
                            propertyValue = property.Converter.ReadJson(reader, property.PropertyType, property.ValueProvider.GetValue(existingValue), serializer);
                        else
                            propertyValue = serializer.Deserialize(reader, property.PropertyType);
                        property.ValueProvider.SetValue(existingValue, propertyValue);
                        break;
                }
            }
        }
    }

    static IEnumerable<JsonProperty> SerializableProperties(JsonObjectContract contract)
    {
        return contract.Properties.Where(p => !p.Ignored && p.Readable && p.Writable);
    }
}

public static partial class JsonExtensions
{
    //https://stackoverflow.com/a/39462464/3744182
    public static JsonReader ReadToContentAndAssert(this JsonReader reader)
    {
        return reader.ReadAndAssert().MoveToContentAndAssert();
    }

    public static JsonReader MoveToContentAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
            reader.ReadAndAssert();
        while (reader.TokenType == JsonToken.Comment) // Skip past comments.
            reader.ReadAndAssert();
        return reader;
    }

    public static JsonReader ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
            throw new JsonReaderException("Unexpected end of JSON stream.");
        return reader;
    }
}

public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((bool)value) ? "1" : "0");
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        var token = JToken.Load(reader);

        if (token.Type == JTokenType.Boolean)
            return (bool)token;
        return token.ToString() != "0";
    }

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

最后,要做:

var orderBook = JsonConvert.DeserializeObject<Dictionary<string, PoloniexPairInfo>>(jsonString);

正在工作 .Net提琴.

这篇关于将JSON解析为C#对象-动态获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 00:50