How to access properties with "." in the name in a dynamic object

1

I have the following JSON object:

{
    "odata.metadata":"httpXXXXX",
    "odata.count":1443,
    "value":[
    { "codigo" : 1 , "nome" : "ABS"}
    ]
}

and create an object like this:

dynamic categorias = JsonConvert.DeserializeObject(jsonResult);

I can access the property value normally but how do I access the odata.count property?

PS: I'm already using the Newtonsoft library to manipulate json.

Thank you.

    
asked by anonymous 09.06.2017 / 15:01

1 answer

4

As a property you will not be able to access it, C # has no mechanism to handle it.

In any case, a dynamic object is nothing more than a set of key-values, so you can access a value by its key, in this way

Remembering this may not be a good idea.

var metadata = categorias["odata.metadata"];

Reading indicated:

Even though you have no control over the payload that will be returned, you will always have to know which properties you want to access. This is sufficient to create a contract class to deserialize JSON.

Here's how it would look:

class RetornoWebservice
{
    [JsonProperty(PropertyName = "odata.metadata")]
    public string Metadata { get; set; }

    [JsonProperty(PropertyName = "odata.count")]
    public string Count { get; set; }

    [JsonProperty(PropertyName = "value")]
    public IEnumerable<Valor> Valores { get; set; }
}

class Valor
{
    [JsonProperty(PropertyName = "codigo")]
    public int Codigo { get; set; }

    [JsonProperty(PropertyName = "nome")]
    public string Nome { get; set; }
}

And the use would be something like

var categorias = JsonConvert.DeserializeObject<RetornoWebservice>(jsonResult);

var metadata = categorias.Metadata;
    
09.06.2017 / 15:14