Serialize to different objects in C#

Asked

Viewed 59 times

0

How I have to create my class in C# to be able to serialize this json that comes in a request for my API?

[{
    "name": "campo_normal_1",
    "value": "valor do campo 1 normal"
},
{
    "name": "campo_lista_1",
    "value": 
    [
        {
            "name": "campo_1_da_lista",
            "value": "valor do campo 1 da lista"
        },{
            "name": "campo_2_da_lista",
            "value": "valor do campo 2 da lista"
        },{
            "name": "campo_3_da_lista",
            "value": 
                    [{
                        "name": "campo_1_da_lista",
                        "value": "valor do campo 1 da lista"
                    },{
                        "name": "campo_2_da_lista",
                        "value": "valor do campo 2 da lista"
                    }]
        }]
}]

Right now I have class this way:

public class FieldRequest
{
    public string name { get; set; }
    public object value { get; set; }
}

In the controller I try to serialize the field value to a list of FieldRequest, but is there a way to get the fields all serialized correctly? I need something like a Overload where my parameter value be a string or a list of FieldRequest.

2 answers

2


Unable to use "one of two types" in C#, as is possible in Typescript. But as you demonstrate that answer, you can use the type Dynamic and run logics for type conditions. For example:

public class FieldRequest
{
    public string name { get; set; }
    public dynamic value { get; set; }
}

Then, you can condition the property type using is:

FieldRequest fieldRequest = Newtonsoft.Json.JsonConvert.DeserializeObject<FieldRequest>(json);

if (fieldRequest.value is FieldRequest) {
  // lógica para quando for um FieldRequest
} else if (fieldRequest.value is string) {
  // lógica para quando for uma string
}

0

Good afternoon!

Maybe something like that here:

// Root myDeserializedClass = Jsonconvert.Deserializeobject(myJsonResponse);

public class Myarray { public string name; public Object value; }

public class Root    {
    public List<MyArray> MyArray; 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.