我想在.NET Core的字符串中将C#对象序列化为JSON.
我已尝试使用此代码,但它会生成带引号的转义字符的字符串:
string s = JsonConvert.SerializeObject(sensorData);
Run Code Online (Sandbox Code Playgroud)
这是结果字符串:
"{\"Id\":\"100201\",\"Timestamp\":\"2018-02-08T08:43:51.7189855Z\",\"Value\":12.3}"
Run Code Online (Sandbox Code Playgroud)
如何在没有像这样的转义字符的情况下将对象序列化为字符串?
"{"Id":"100201","Timestamp":"2018-02-08T08:43:51.7189855Z","Value":12.3}"
Run Code Online (Sandbox Code Playgroud) 我已经将Web服务迁移到.NET Core 2.0,它可以正常工作,但是在以json字符串获取响应时遇到问题。
api上的方法:
[HttpGet]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(EntityNotFoundErrorResult), 404)]
public async Task<IActionResult> GetCurrenciesAsync()
{
var result = await service.GetByTypeAsync(ObjectType.Currency.ToString());
return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)
返回正确的json为result:
"{\"elements\": [{\"Id\": \"1\", \"Symbol\": \"PLN\"},{\"Id\": \"2\", \"Symbol\": \"SIT\"}]}"
Run Code Online (Sandbox Code Playgroud)
然后在客户端上,我正在使用服务堆栈来获取我的货币作为字符串:
public virtual IEnumerable<CurrencyData> GetCurrencies()
{
string response = null;
try
{
response = api.Get<string>("/Currencies");
}
catch (Exception e)
{
}
return string.IsNullOrEmpty(response) ? null : JsonConvert.DeserializeObject<TempCurrencyClass>(response).elements;
}
Run Code Online (Sandbox Code Playgroud)
而response看起来像这样:
"\"{\\\"elements\\\": [{\\\"Id\\\": \\\"1\\\", \\\"Symbol\\\": \\\"PLN\\\"},{\\\"Id\\\": \\\"2\\\", \\\"Symbol\\\": \\\"SIT\\\"}]}\""
Run Code Online (Sandbox Code Playgroud)
因此JsonConvert.DeserializeObject抛出反序列化异常:
Newtonsoft.Json.JsonSerializationException
Run Code Online (Sandbox Code Playgroud)
但是当我反序列化对刺痛和目标的回应时,它起作用:
var …Run Code Online (Sandbox Code Playgroud) 我有以下控制器和操作。
[Route("/api/simple")]
public class SimpleController : Controller
{
[HttpGet]
[Route("test")]
public string Test()
{
return "test";
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用它时,我希望有操作返回"test"(这是有效的JSON),但是它会返回test(不带引号),这是有效的行为还是错误?我想念什么吗?
GET http://localhost:5793/api/simple/test HTTP/1.1
User-Agent: Fiddler
Host: localhost:5793
Accept: application/json
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sun, 09 Aug 2015 14:37:45 GMT
Content-Length: 4
test
Run Code Online (Sandbox Code Playgroud)
注意:对于ASP.NET Core 2.0+,当请求中存在Accept标头时,此方法不适用-但是,如果省略了Accept标头并且进行了内容协商,则仍然适用。