简体   繁体   中英

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, ie 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, eg like this:

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

I have to serialize twice, ie :

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?

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.

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM