user1301428
user1301428

Reputation: 1783

How to send a PUT request with a nested JSON payload in C#?

I am trying to send a PUT request inside my C# application, and the body of the request should be in JSON format. Things are working just fine for JSON payloads that are in very simple format, i.e. like this:

{
    id: 1,
    title: 'foo',
    body: 'bar',
    userId: 1
}

This is the code I have written to handle this scenario:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
       var serializer = new JavaScriptSerializer();
       string json = serializer.Serialize(new
       {
            id = "1",
            title = "foo",
            body = "bar",
            userId = "1"
        });
        streamWriter.Write(json);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Now, if I want to create a payload with a different JSON format, e.g. like this:

{
    object =
    {
        id = "1"
        title = "foo",
        body = "bar",
        userId = "1"
    }
}

I have to serialize twice, i.e. :

var serializer = new JavaScriptSerializer();
var serializer1 = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
     object = serializer1.Serialize(new
     {
          test = "test"
          title = "foo",
          body = "bar",
          userId = "1"
      }),             
});

But it doesn't look very efficient. Is there a better way to do this?

Upvotes: 1

Views: 1021

Answers (2)

Eser
Eser

Reputation: 12546

You don't need double serialization. The object you should serialize is

new {
    @object = new  {
        id = "1",
        title = "foo",
        body = "bar",
        userId = "1"
    }
}

Upvotes: 1

Evk
Evk

Reputation: 101443

Well you better use something better than JavaScriptSerializer, like Json.NET. But anyway even with that one you don't need to serialize twice, just do:

string json = serializer.Serialize(new {
    @object = new
    {
       id = "1",
       title = "foo",
       body = "bar",
       userId = "1"
    }});

Actually when serializing twice you produce wrong json: "object" will be just a string containing json, not json object.

Upvotes: 2

Related Questions