Jam*_*ood 10 c# asp.net json.net
什么应该HttpContentExtensions.ReadAsAsync<string>和HttpContent.ReadAsStringAsync用于什么?
他们似乎做了类似的事情,但以奇怪的方式工作.下面是几个测试及其输出.在某些情况下JsonReaderException,抛出某些情况下会输出JSON但带有其他转义字符.
我最终在我的代码库中使用了这两个函数,但如果我能理解它们应该如何工作,我希望能在一个函数上保持一致.
//Create data and serialise to JSON
var data = new
{
message = "hello world"
};
string dataAsJson = JsonConvert.SerializeObject(data);
//Create request with data
HttpConfiguration config = new HttpConfiguration();
HttpRequestMessage request = new HttpRequestMessage();
request.SetConfiguration(config);
request.Method = HttpMethod.Post;
request.Content = new StringContent(dataAsJson, Encoding.UTF8, "application/json");
string requestContentT = request.Content.ReadAsAsync<string>().Result; // -> JsonReaderException: Error reading string.Unexpected token: StartObject.Path '', line 1, position 1.
string requestContentS = request.Content.ReadAsStringAsync().Result; // -> "{\"message\":\"hello world\"}"
//Create response from request with same data
HttpResponseMessage responseFromRequest = request.CreateResponse(HttpStatusCode.OK, dataAsJson, "application/json");
string responseFromRequestContentT = responseFromRequest.Content.ReadAsAsync<string>().Result; // -> "{\"message\":\"hello world\"}"
string responseFromRequestContentS = responseFromRequest.Content.ReadAsStringAsync().Result; // -> "\"{\\\"message\\\":\\\"hello world\\\"}\""
//Create a standalone new response
HttpResponseMessage responseNew = new HttpResponseMessage();
responseNew.Content = new StringContent(dataAsJson, Encoding.UTF8, "application/json");
string responseNewContentT = responseNew.Content.ReadAsAsync<string>().Result; // -> JsonReaderException: Error reading string.Unexpected token: StartObject.Path '', line 1, position 1.
string responseNewContentS = responseNew.Content.ReadAsStringAsync().Result; // -> "{\"message\":\"hello world\"}"
Run Code Online (Sandbox Code Playgroud)
ReadAsStringAsync:这是一个基本的"让我把内容作为一个字符串"的方法.它会对你抛出的任何东西起作用,因为它只是字符串.
ReadAsAsync<T>:这用于将JSON响应反序列化为对象.失败的原因是因为返回中的JSON不是单个字符串的有效JSON表示.例如,如果序列化字符串:
var result = JsonConvert.SerializeObject("hello world");
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
输出是:
"hello world"
Run Code Online (Sandbox Code Playgroud)
请注意它是如何被双引号括起来的.如果您尝试将任意JSON直接反序列化为不符合格式的字符串,"....."则会抛出您看到的异常,因为它期望JSON以a开头".
| 归档时间: |
|
| 查看次数: |
3107 次 |
| 最近记录: |