A
A
Atlant1Q2018-02-02 15:48:33
JSON
Atlant1Q, 2018-02-02 15:48:33

How to deserialize a request?

The following request comes from the front:
[{"form_name":"form1","value":"buy"},{"form_name":"form2","value":"osago"},{"form_name":" form3","value":"msk"},{"form_name":"form6","value":{"name":"vaprpva","phone":"+7 (999) 999-99-99" ,"date":"02.02.2018","time":"16:00 - 17:00","comment":""}}]
deserialize like this:

ActionResult Test(FormCollection collection){
string request = collection["test"]; //в request вышеуказанный запрос
var req = JsonConvert.DeserializeObject<List<Form>>(request);

Form class:
public class Form
{
public string form_name { get; set; }
public string value { get; set; }
}

until form6 comes with a complex value, everything is fine. Tell me how to do the deserialization correctly so that it turns out to parse the value with form6 ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-02-02
@kttotto

There are several options.
The first one is, as written in the post above, to lead to dynamic. But this option has a drawback - at every moment you need to know which field has arrived, otherwise you will get an exception at the runtime level. But to know this, apparently, is not real.
Second, is to convert to

public string form_name { get; set; }
public object value { get; set; }

In principle, this is almost the same option as the first one, because the dynemic is the same object, it just does not pass type checking at the compilation level. And then cast value to a previously known type, make a switch so that the logic is something like this
response.value = response.value as string;
if(response.value == null)
{
     response.value = response.value as SomeClass;
     if(response.value == null)
     {
         response.value =  response.value as OtherClass;
   ....

But this method also has a drawback, you need to know exactly what types can come in value.
And the third option is to cast value to JObject and manually pull out the necessary nodes with the value.
PS. And yet, I would not recommend naming the model by adjusting to json. Newton has the necessary attributes for this.
public class Form
{
  [PropertyName = "form_name")]
  public string FormName { get; set; }
  
  [PropertyName = "value")]
  public string Value { get; set; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question