Reputation: 5031
using (var streamWriter = new StreamWriter(SomeRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(new
{
Type_member1 = "StacOverFlow",
Type_member2 = sometext,
Type_member3 = 0,
private = true
});
streamWriter.Write(json);
}
As you can see, there is Type member called "private". Of course, when i typed it, a message will pop-up and tell me:
"Invalid expression term 'private'"
Putting "private" inside quote will return this error:
"Invalid anonymous type member declarator. bla bla bla..."
Is there a way to solve this?
Upvotes: 0
Views: 68
Reputation: 10849
private
is a reserved keyword of C# framework and can not it used as identifier in program. If you try to write string private = "sometext";
then compiler will throw exception by own stating Identifier 'private' is a keyword
.
So you should define the prop name as @private
Or you should inform serialize to name it as private at time of serialization.
Upvotes: 2
Reputation: 61885
This can be solved by using the syntax:
@private = true,
Note the use of @private
(where the @ changes how the compiler interprets the source code); and changing the ;
to a ,
to avoid the other syntax error.
Keywords [ie.
private
] are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example,@if
[ie.@private
] is a valid identifier butif
[ie.private
] is not because if is a keyword.
Alternative, create a non-anonymous type (with a better code-friendly member name) and apply a [JsonProperty]
or [DataMember]
attribute to change the serialized name to 'private'.
Upvotes: 6