gpt4 book ai didi

c# - 使用 Json.NET 反序列化带有数组数组的 json 字符串

转载 作者:太空狗 更新时间:2023-10-29 21:39:31 25 4
gpt4 key购买 nike

string json = @"{
'symbol':'XX',
'column_names":["Date","Open","High","Low","Close","Volume"],
'data':[
['2014-01-02',25.78,25.82,25.47,25.79,31843697.0],
['2013-12-31',25.81,26.04,25.77,25.96,22809682.0]]}";

public class DailyData
{
public string symbol { get; set; }
public List<OneDay> data { get; set; }
}

public class OneDay
{
public DateTime date { get; set; }
public double open { get; set; }
public double high { get; set; }
public double low { get; set; }
public double close { get; set; }
public double volume { get; set; }
}

DailyData dd = JsonConvert.DeserializeObject<DailyData>(json);

这是我的 json 字符串和类,我正在尝试将其反序列化为 Json.net .如果我更改 public List<OneDay> data { get; set; } 它将起作用至 public List<object> data { get; set; } .但在这种情况下,我必须进一步执行更多步骤。是否有一个巧妙的解决方案来一次性反序列化它?

最佳答案

是的,您必须使用 JsonConverter 类来告诉反序列化器如何将值数组映射到 OneDay 类。

示例:

void Main()
{
string json = @"{
'symbol':'XX',
'column_names':['Date','Open','High','Low','Close','Volume'],
'data':[
['2014-01-02',25.78,25.82,25.47,25.79,31843697.0],
['2013-12-31',25.81,26.04,25.77,25.96,22809682.0]
]
}";

DailyData dd = JsonConvert.DeserializeObject<DailyData>(json);
dd.Dump();
}

class OneDayJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
OneDay obj = new OneDay();
obj.date = reader.ReadAsDateTime() ?? DateTime.MinValue;
obj.open = (double)(reader.ReadAsDecimal() ?? 0);
obj.high = (double)(reader.ReadAsDecimal()?? 0);
obj.low = (double)(reader.ReadAsDecimal() ?? 0);
obj.close = (double)(reader.ReadAsDecimal() ?? 0);
obj.volume = (double)(reader.ReadAsDecimal() ?? 0);
reader.Read();
return obj;
}

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

public class DailyData
{
public string symbol { get; set; }
public List<OneDay> data { get; set; }
}

[JsonConverter(typeof(OneDayJsonConverter))]
public class OneDay
{
public DateTime date { get; set; }
public double open { get; set; }
public double high { get; set; }
public double low { get; set; }
public double close { get; set; }
public double volume { get; set; }
}

结果:

enter image description here

关于c# - 使用 Json.NET 反序列化带有数组数组的 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20903966/

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