user350213
user350213

Reputation: 385

Serialize JSON from dynamic ignoring a C# keyword

I'm using Json.net and all I need from it is the simplest form of creating a JSON string to send up as an HTTP POST. For that reason, I don't want to create a new custom object just to be able to serialize it correctly. So I chose the dynamic method in Json.net.

The JSON that I need looks something like this:

{
  root: {
    header: {
        namespace: "",
        name: ""
        },
    body:   {
        email: email
        myArray:[
            {
                item1: "",
                item2: ""
            },
            {
                item3: "",
                item4: ""
            },
        ]
        }
    }
}

So I tried to do the following:

dynamic httpRequestBody = new JObject();
httpRequestBody.root = new JObject();
httpRequestBody.root.header = new JObject();
httpRequestBody.root.header.namespace = "";
httpRequestBody.root.header.name = "name;

But since "namespace" is a C# keyword, it doesn't let me use it. Is there a way to get around it since I need "namespace" as part of the JSON? If not, what's the simplest way of creating this JSON string?

To clarify, I don't have a very strong opinion against creating my own little class and serialize it, but it feels like since all i need is to send some jSON up and forget about it, I should be able to create it on the fly.

Upvotes: 2

Views: 48

Answers (1)

dbc
dbc

Reputation: 116991

Rather than upcasting your JObject to be dynamic, keep it as an explicitly typed variable. JObject implements IDictionary<string, JToken> which can be used, along with the implicit conversion operators from primitive types to JToken, to set a property value of any name to any primitive value or other JToken:

var header = new JObject();
header["namespace"] = ""; // Here we use the implicit operator from string to JToken
header["name"] = "name";

httpRequestBody["root"]["header"] = header;

Using explicit typing also allows for compile-time checking of code correctness, and may improve performance.

Demo fiddle here.

Upvotes: 1

Related Questions