我想在 ASP .Net Core 控制器輸出上以字串形式發送原始 Json 內容。
如果我嘗試通過回傳字串本身來執行此操作,則其內容中的雙引號將被轉義,并且客戶端不會將其識別為 Json 內容,而是將其識別為字串。例如。:
public async Task<ActionResult<MyClass>> Get()
{
try
{
// here we build an object from a service with a complex dataset
MyClass myObject = ...; // business code here
// serializing the object
JsonSerializerOptions options = new()
{
WriteIndented = true,
ReferenceHandler = ReferenceHandler.IgnoreCycles
};
string jsonDataset = JsonSerializer.Serialize<MyClass>(myObject , options);
// or we could do simply for testing something like: jsonDataset = "{\"Id\"=10, \"Label\"=\"HelloWorld!\"}";
// then we send it to the client
return Ok(jsonDataset);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
我無法反序列化 json,它對于參考其他物件的物件串列來說太復雜了。
我不能使用 NewtonSoft 庫,這對我的專案客戶來說是不行的。所以這里沒有用于反序列化的匿名類:[|]
有沒有辦法將字串“jsonObject”輸出為應用程式/json 內容但沒有雙引號轉義?
謝謝你的幫助!
uj5u.com熱心網友回復:
您可以使用這些Content方法回傳字串并指定內容型別:
return Content(
jsonDataset,
"application/json");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511748.html
