U
U
userrocker2015-09-28 13:14:28
JSON
userrocker, 2015-09-28 13:14:28

How to parse json in strongly typed languages?

The question has been a bone in the throat for a long time. How do we usually parse json? We write a data model, for example C #:
{result: 0}

[JsonObject(MemberSerialization.Fields)]
public class Response
{
    [JsonProperty(PropertyName="result")]
    int Result;
}

... and so on to taste. But what if in one case result is an int and in the other case it is an object. All logic is already broken.
{result: {param1:0, param2:"hello"}
[JsonObject(MemberSerialization.Fields)]
public class Response
{
    [JsonProperty(PropertyName="result")]
    Result Result;
}
[JsonObject(MemberSerialization.Fields)]
public class Result
{
    [JsonProperty(PropertyName="param")]
    int Param;
//итд
}

And now what? Parse 2 times and catch in try-catch? check somehow? and if there can be both int, and string, and object - parse 3 times? When to stop?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lyeskin, 2015-09-28
@lyeskin

There are mini-libraries for parsing JSON.

V
Vladimir Io, 2015-09-28
@vawsan

One of the simplest options without any plugins (but only if you know the nesting you need) is to serialize the data into a Dictionary and then typeof.
But, again, you need to understand how you can distinguish a "0" string from a "0" digit. If the structure itself does not allow this, then it is no longer an option ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question