Removing custom array deserialization using RestSharp / JSON.NET

I use RestSharp / JSON.NET to communicate with an API that returns such a collection:

{ "count": 100, "0": { "title":"some title" }, "1": { "title":"some title" }, .... } 

Instead of the usual format:

 { "count": 100, "items": [ { "title":"some title" }, { "title":"some title" }, .... ] } 

Is there an easy way to get RestSharp / JSON.NET to parse the first example correctly, i.e. to the property of the Item [] element on my deserialized object?

Do I need to write my own deserializer?

+4
source share
2 answers

Do you have control over the API? Can you change it? The way you get items seems very strange to me. You do not get a collection of objects, but individual objects of the same type. I mean, your BO will look like it displays what you get:

  class YourBO { int count; YourProperty prop0; YourProperty prop1; ... } 

Instead of getting a set of properties, as would be the case with the second example:

  class YourBO { int count; IEnumerable<YourProperty> props; } 

So, unless you have a finite and known number of elements, the json design you get does not make sense

0
source

This collection does not obey the regular json format, so some reevaluation of json net is required. You may be able to write a custom json net custom convector converter, then you can get it in RestSharp.

Or you could take the whole object as a JObject, which would at least provide you with an object that you could skip and convert to a list.

Although this is essentially the same as a custom deserializer, you just get it into a very general object first and from there is better than working with a string :)

0
source

Source: https://habr.com/ru/post/1392116/


All Articles