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

Asked

Viewed 353 times

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 property odata.count ?

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

Grateful.

  • Bah, you really need to use dynamic?

  • Since I don’t have control of the JSON being generated, I understand that I do. Even if I were going to create a class, what do I do with these properties with "." in the middle of the name?

  • If you were to create a class to represent, you would define a pointless name for the class and make a mapping with the original name.

  • 1

    You don’t have control of the JSON being generated, but you know which properties you want to access, you don’t know?

  • Um, I got the idea. I think I can solve in mapping.

  • I left an example.

Show 1 more comment

1 answer

4


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

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

Remembering that this might not be a good idea.

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

Indicated reading:


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

See 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;
  • Excellent! Thank you very much!

Browser other questions tagged

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