【发布时间】:2019-01-26 02:15:40
【问题描述】:
我想通过解析包含嵌入式 contianer 对象的 Json 字符串来创建 C# 对象。查看代码 sn-p 中的 StockHistory。
我尝试以编译器允许的多种方式定义父对象。就像在列表中包装和不包装“KeyValue 属性”一样,使用字典也可以用单引号和双引号定义字符串。大多数 Stackoverflow 列表显示一个列表或字典作为父对象(contianer)。但是我的容器是嵌入的。
但是,如果需要自定义转换器...我不确定如何编写它。一个代码 sn-p 会很棒。我无法更改 Json……它来自第三方服务器。
当我使用 Visual Studio 2017 JSON Visualizer(通过突出显示变量并单击放大草)检查 json 字符串时,一切看起来都很好并且符合预期。
using Newtonsoft.Json; // I'm using NuGet vs: 12.0.0.0
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
public class StockHistory
{
public List<string> Meta_Data { get; set; }
public Dictionary<string, LHOCV> Lhocv { get; set; }
}
public class LHOCV
{
public float Low { get; set; }
public float High { get; set; }
public float Open { get; set; }
public float Close { get; set; }
public double Volume { get; set; }
}
static void Main(string[] args)
{
string json =
@"{
'Meta Data': {
'1. Information': 'Intraday (5min) ...',
'2. Symbol': 'MSFT',
'3. Last Refreshed': '2019-01-22 16:00:00',
'4. Interval': '5min',
'5. Output Size': 'Full size',
'6. Time Zone': 'US/Eastern'
},
'Time Series (5min)': {
'2019-01-22 16:00:00': {
'1. open': '105.2200',
'2. high': '105.8700',
'3. low': '105.1000',
'4. close': '105.8200',
'5. volume': '1619877'
},
'2019-01-22 15:50:00': {
'1. open': '105.4200',
'2. high': '105.4800',
'3. low': '105.2600',
'4. close': '105.3000',
'5. volume': '452625'
}
}
}";
StockHistory a = JsonConvert.DeserializeObject<StockHistory>(json);
// I can not get a value assigned to "a"... both container objects,
// Meta_Data and Lhocv, are rendered null.
//Console.WriteLine(a.Lhocv["2019-01-22 16:00:00"].High);
}
}
}
我希望 c# 变量“a”(StockHistory)包含解析的 JSON 键和 JSON 字段“元数据”和“时间序列(5 分钟)”的数据。
我得到的是容器的空值。
【问题讨论】: