S
S
stalerum2016-05-24 15:30:23
JSON
stalerum, 2016-05-24 15:30:23

JSON.NET How to write a class where field in json can have different data type?

When requesting the same link, different answers may come.
For example:
{"data":"blablabla","text":"lorem ipsum"}
{"data":[{"item":"one"},{"item":"two"}],"text" :"lorem ipsum"}
I use a deserializer and have to write classes.
In the first case, data is a string, in the second, an array.
But what type should data have in this case, so that with different answers I can get the result? Moreover, I cannot know in advance which option will come in response.
Or there should be some kind of condition, but I don't know how to tie it here.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Eremin, 2016-05-24
@stalerum

I had a similar problem .
I solved it using dynamic .
We fill it with json, and there, at our own peril and risk, we describe the processing logic in case it came or something came in
more about dynamic

G
Georgy Pelageykin, 2016-05-24
@ArXen42

You can try to make data an Object type, but it's not a fact that runtime serialization will pick up this business. And then work with it in the style of if (data.GetType.IsArray) ... (what a horror).
But I think this is a bad approach. If different data comes, you need to do different entities as well. Although, of course, it depends on the context of the task, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question