如何在C#中使用嵌套的JSON有效负载发送PUT请求?

时间:2016-04-01 22:18:01

标签: c# json

我正在尝试在C#应用程序中发送PUT请求,并且请求的主体应该是JSON格式。对于格式非常简单的JSON有效负载,情况正常,例如:

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

这是我为处理这种情况而编写的代码:

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();

现在,如果我想创建一个具有不同JSON格式的有效负载,例如像这样:

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

我必须序列化两次,即:

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"
      }),             
});

但它看起来并不高效。有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

嗯,你最好使用比JSON.NET更好的JavaScriptSerializer。但无论如何,即使使用那个,您也不需要序列化两次,只需执行:

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

实际上,当序列化两次时你产生错误的json:“object”将只是一个包含json的字符串,而不是json对象。

答案 1 :(得分:1)

您不需要双序列化。您应序列化的对象是

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