使用ObjectContent问题序列化JSON

时间:2017-06-27 00:30:46

标签: c# json asp.net-web-api serialization json.net

我编写了一个HTTP客户端库,供我们现有的一个进程使用。它在正文中发送带有JSON内容的发布请求。填充请求内容和对象本身的代码如下所示。

… 
        HttpRequestMessage httpMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost");
        MyWireObject request = new MyWireObject()
        {
            Email = "user@test.com",
            Document = JToken.Parse(@"{""content"": ""data"", ""content2"": ""data2""}")
        };
        httpMessage.Content = new ObjectContent(typeof(MyWireObject), request, new JsonMediaTypeFormatter());
        //httpMessage.Content = new StringContent(JToken.FromObject(request).ToString(), Encoding.UTF8, "application/json");

        var content = httpMessage.Content;
        string jsonContent = content.ReadAsStringAsync().Result;
…

public class MyWireObject
{
    [JsonProperty(PropertyName = "Email")]
    public string Email
    {
        get; set;
    }

    [JsonProperty(PropertyName = "Document")]
    public JToken Document
    {
        get; set;
    }
}

当我使用我写的独立exe的客户端库时,它很好地序列化了JSON。但是当我将它与现有进程集成时,结果(在jsonContent中捕获)看起来像这样:

{"Email":"user@test.com","Document":{"content":[],"content2":[]} }

基本上,JToken字段的所有值都将丢失。如果我使用StringContent而不是ObjectContent,就像在注释行中一样,它可以工作。

我可以想到我的独立exe和现有流程之间的一个区别是该流程在网络服务帐户下运行。这是由于帐户许可吗?或者我使用它错了?或者是由于.NET或Newtonsoft.Json.Linq中的一些已知错误?

感谢。

1 个答案:

答案 0 :(得分:0)

为什么不采用不同的方法并使用Newtonsoft.Json:

using Newtonsoft.Json;

// First define the classes you will need ...

public class Document
{
    public string Content1 { get; set; }
    public string Content2 { get; set; }
    // ...
}

public class MyWireObject
{
    public string Email { get; set; }
    public Document Document { get; set; }
}

// Later, create an instance and serialize it as the body of your request ...

HttpRequestMessage httpMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost");
MyWireObject myWireObject = new MyWireObject() 
{
    Email = "user@test.com",
    Document = new Document() 
    {
        Content1 = "content1",
        Content2 = "content2",
        // ...
    }
};

httpMessage.Content = JsonConvert.SerializeObject(myWireObject);

// Later in the POST handler ...

string myWireObjectAsString = httpMessage.Content.ReadAsStringAsync().Result;

// Or even better ...

MyWireObject myWireObject = JsonConvert.DeserializeObject<MyWireObject>(myWireObjectAsString);

// And use the object ...