gpt4 book ai didi

c# - 将 JSON 解析为 C# 对象 - 动态获取属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:10 33 4
gpt4 key购买 nike

(跳到粗体部分以获得一句话 tl;dr :)

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

  • BTC_AMP 之类的货币对列表永远持续下去,为了举例,我将其截断
  • BTC_AMP 似乎是一个包含一些字段的 NAMED OBJECT。

    {
    "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 很好地映射对象如所述here .我的问题是,在我看来,我需要为一千个货币对创建一个对象并预定义属性名称,例如 BTC_AMPBTC_ARDR 等。

您可能会看到我的目标...如何在不预先创建每一对名称的情况下映射此对象?

希望我在这里遗漏了一些明显的东西。

编辑:代码看起来像这样,我不想做的事:

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...如果我在某处有一个货币对列表,我至少可以动态创建一个对象/对象的属性吗?似乎没有手写那么可笑。

最佳答案

这里有几个问题:

  • 您的根对象具有大量可变数量的属性,其值对应于固定数据类型 PoloniexPairInfo .由于您不想创建对所有这些属性进行硬编码的根类型,因此您可以反序列化为 Dictionary<string, PoloniexPairInfo>如图Create a strongly typed c# object from json object with ID as the name .

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

    [
    [
    "0.00007359",
    163.59313969
    ]
    ]

    您想将内部数组映射到固定的 POCO PoloniexPriceVolume通过将特定数组索引处的值绑定(bind)到特定的 C# 属性。您可以使用 ObjectToArrayConverter<PoloniexPriceVolume> 执行此操作来自 C# JSON.NET - Deserialize response that uses an unusual data structure .

  • 最后,JSON值"isFrozen"有一个字符串值“0”,但您想将其映射到 boolpublic bool IsFrozen { get; set; } .您可以通过调整 BoolConverter 来做到这一点来自 Convert an int to bool with Json.Net .

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

[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 fiddle .

关于c# - 将 JSON 解析为 C# 对象 - 动态获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45404111/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com