首页 > 解决方案 > 2 种格式的 JSON 字符串

问题描述

String quoteIn = "{\"T\":\"q\",\"S\":\"AAPL\",\"bx\":\"Q\",\"bp\":145.67,\"bs\":14,\"ax\":\"K\",\"ap\":145.68,\"as\":6,\"c\":[\"R\"],\"z\":\"C\",\"t\":\"2021-08-10T18:49:47.469842Z\"}";
String quoteIn2 = "{\"T\":\"q\",\"S\":\"AAPL\",\"bx\":\"Q\",\"bp\":145.6,\"bs\":13,\"ax\":\"P\",\"ap\":145.61,\"as\":11,\"c\":[\"R\"],\"z\":\"C\",\"t\":\"2021-08-10T19:07:30.681679Z\"},{\"T\":\"q\",\"S\":\"AAPL\",\"bx\":\"Q\",\"bp\":145.6,\"bs\":13,\"ax\":\"P\",\"ap\":145.61,\"as\":10,\"c\":[\"R\"],\"z\":\"C\",\"t\":\"2021-08-10T19:07:30.681713152Z\"}";

做一个简单的演示
格式1:{"T":"q",...}
格式2:{{"T":"q",...}, {"T":"q",...}}

问题是如何处理它们?\

如果格式 1,我使用以下内容:

var quote = JsonConvert.DeserializeObject<Quote>>(quoteIn);

哪个有效

但如果格式 2,我使用以下内容:

var quote2 = JsonConvert.DeserializeObject<List<Quote>>(quoteIn2);

然后它错误地说:

ex.Message  "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[JasonTest.Quote]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'T', line 1, position 5." string

请帮忙!

标签: c#json

解决方案


格式 2 不是有效格式,也不是数组:

{{"T":"q",...}, {"T":"q",...}}

应该:

[{"T":"q",...}, {"T":"q",...}]

推荐阅读