G Chu
G Chu

Reputation: 491

JSON string with 2 formats

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\"}";

make a simple presentation
format 1: {"T":"q",...}
format 2: {{"T":"q",...}, {"T":"q",...}}

Question is how to process both of them?\

If format 1, I use the following:

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

which works

but if format 2, I use the following:

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

then it error out saying:

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

Please help!

Upvotes: 0

Views: 74

Answers (2)

G Chu
G Chu

Reputation: 491

I used System.text.jason to fixed above issue.

Use Jsondocument JsonElement.ArrayEnumerator to loop through each one of them

and use JasonElement.GetRawText to get string and deserialize into a C# class instance.

Only downside is you have to upgrade project to .Net Core 5.0

Upvotes: 0

Thomas
Thomas

Reputation: 10055

Format 2 is not a valid format and not an array:

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

should be:

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

Upvotes: 3

Related Questions