【发布时间】:2021-10-05 15:04:22
【问题描述】:
我有一个无效的 JSON,我需要使用 Newtonsoft 进行解析。问题是 JSON 没有使用正确的数组,而是包含数组中每个条目的重复属性。
我有一些工作代码,但真的不确定这是要走的路还是有更简单的方法?
无效的 JSON:
{
"Quotes": {
"Quote": {
"Text": "Hi"
},
"Quote": {
"Text": "Hello"
}
}
}
我试图序列化的对象:
class MyTestObject
{
[JsonConverter(typeof(NewtonsoftQuoteListConverter))]
public IEnumerable<Quote> Quotes { get; set; }
}
class Quote
{
public string Text { get; set; }
}
JsonConverter的读取方法
public override IEnumerable<Quote> ReadJson(JsonReader reader, Type objectType, IEnumerable<Quote> existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var quotes = new List<Quote>();
while (reader.Read())
{
if (reader.Path.Equals("quotes", StringComparison.OrdinalIgnoreCase) && reader.TokenType == JsonToken.EndObject)
{
// This is the end of the Quotes block. We've parsed the entire object. Stop reading.
break;
}
if (reader.Path.Equals("quotes.quote", StringComparison.OrdinalIgnoreCase) && reader.TokenType == JsonToken.StartObject)
{
// This is the start of a new Quote object. Parse it.
quotes.Add(serializer.Deserialize<Quote>(reader));
}
}
return quotes;
}
我只需要读取带有重复键的 JSON,而不需要写入。
【问题讨论】:
-
您需要用重复键编写 JSON,还是只读取?
-
@dbc 刚刚阅读。