我在 WebApi 控制器中编写了以下操作:
public JsonResult GetData()
{
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var item = new Item();
item.GenerateData();
var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
UseDataContractJsonSerializer = true
};
var jsonSerializer = new JsonSerializer();
var serializedData = jsonSerializer.Serialize(jsonMediaTypeFormatter, item);
var jsonResult = new JsonResult
{
ContentType = "application/json",
Data = serializedData,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
};
return jsonResult;
}
该行: var serializedData = jsonSerializer.Serialize(jsonMediaTypeFormatter, item);
将数据序列化为 Json,因此我有:
{"Class":{"Valid":{"From":"\/Date(1363302000000+0100)\/","To":"\/Date(43017433200000+0100)\/"},"Code":3,"Id":3,"Name":"Class3"},
等等..(不是完整的Json)
但是 JsonResult 返回的 Json 不同:
{"ContentEncoding":null,"ContentType":"application\/json","Data":"{\"Class\":{\"Valid\":{\"From\":\"\\\/Date(1363302000000+0100)\\\/\",\"To\":\"\\\/Date(43017433200000+0100)\\\/\"},\"Code\":3,\"Id\":3,\"Name\":\"Class3\"},
注意文本中的“”。为什么会这样?如何更改它?我无法弄清楚..
编辑 JsonSerializer JsonSerializer 是我的助手类,它使用 DataContractJsonSerializer 将数据序列化为 Json,其代码如下:
public class JsonSerializer
{
public string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
}
我想要的是它的执行结果——并且没有被改变——返回给用户