How to set/get the property 'object' of a dynamic object?
dynamic json = new ExpandoObject();
json.foo = "bar"; // OK
json.object = "content"; // Does not compile
json["object"] = "content"; // throw RuntimeBinderException
((IDictionary<string, object>)json)["object"] = "content"; // OK, but ...
I am trying to access a REST api, that require me to set a property named 'object'. The last solution actually fixes the problem, but I feel I'm missing something.
object
is C# keyword.
In order to define object
property, you can tell compiler that "object" is a property name in that case, not keyword by using "@":
json.@object = "content";
It works for all keywords: json.@foreach
, json.@if
, json.@var
etc.
However, it is strongly recommended to minimize its usage, since it worsens readability. If you want an object
property in your output JSON, you could define a class for serialization and use JsonPropertyAttribute
to tell serializer to serialize it as object
:
public class SomeClass
{
[JsonProperty("object")]
public string ObjectContent { get;set; }
}
which will result into
{
"object": "content"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.