Jer*_*och 6 c# json .net-core-3.1 system.text.json
我们有一个 API,它只是将传入的 JSON 文档发布到消息总线,并为每个文档分配了一个 GUID。我们正在从 .Net Core 2.2 升级到 3.1,并打算用新System.Text.Json库替换 NewtonSoft 。
我们反序列化传入的文档,将 GUID 分配给字段之一,然后在发送到消息总线之前重新序列化。不幸的是,重新序列化失败了,例外Operation is not valid due to the current state of the object。
这是一个显示问题的控制器:-
using System;
using System.Net;
using Project.Models;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Text;
using System.Text.Json;
namespace Project.Controllers
{
[Route("api/test")]
public class TestController : Controller
{
private const string JSONAPIMIMETYPE = "application/vnd.api+json";
public TestController()
{
}
[HttpPost("{eventType}")]
public async System.Threading.Tasks.Task<IActionResult> ProcessEventAsync([FromRoute] string eventType)
{
try
{
JsonApiMessage payload;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) {
string payloadString = await reader.ReadToEndAsync();
try {
payload = JsonSerializer.Deserialize<JsonApiMessage>(payloadString);
}
catch (Exception ex) {
return StatusCode((int)HttpStatusCode.BadRequest);
}
}
if ( ! Request.ContentType.Contains(JSONAPIMIMETYPE) )
{
return StatusCode((int)HttpStatusCode.UnsupportedMediaType);
}
Guid messageID = Guid.NewGuid();
payload.Data.Id = messageID.ToString();
// we would send the message here but for this test, just reserialise it
string reserialisedPayload = JsonSerializer.Serialize(payload);
Request.HttpContext.Response.ContentType = JSONAPIMIMETYPE;
return Accepted(payload);
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
JsonApiMessage 对象定义如下:-
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Project.Models
{
public class JsonApiMessage
{
[JsonPropertyName("data")]
public JsonApiData Data { get; set; }
[JsonPropertyName("included")]
public JsonApiData[] Included { get; set; }
}
public class JsonApiData
{
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("attributes")]
public JsonElement Attributes { get; set; }
[JsonPropertyName("meta")]
public JsonElement Meta { get; set; }
[JsonPropertyName("relationships")]
public JsonElement Relationships { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
示例调用如下所示:-
POST http://localhost:5000/api/test/event
Content-Type: application/vnd.api+json; charset=UTF-8
{
"data": {
"type": "test",
"attributes": {
"source": "postman",
"instance": "jg",
"level": "INFO",
"message": "If this comes back with an ID, the API is probably working"
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我payload在 Visual Studio 中检查断点处的内容时,它在顶层JsonElement看起来不错,但这些位看起来不透明,所以我不知道它们是否已被正确解析。它们的结构可能会有所不同,因此我们只关心它们是否是有效的 JSON。在旧的 NewtonSoft 版本中,它们是JObjects。
添加 GUID 后,payload在断点处检查时它会出现在对象中,但我怀疑该问题与对象中的其他元素为只读或类似内容有关。
dbc*_*dbc 10
您的问题可以通过以下更小的示例重现。定义以下模型:
public class JsonApiMessage
{
public JsonElement data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后尝试反序列化并重新序列化一个空的 JSON 对象,如下所示:
var payload = JsonSerializer.Deserialize<JsonApiMessage>("{}");
var newJson = JsonSerializer.Serialize(payload, new JsonSerializerOptions { WriteIndented = true });
Run Code Online (Sandbox Code Playgroud)
你会得到一个例外(demo fiddle #1 here):
public class JsonApiMessage
{
public JsonElement data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
问题似乎JsonElement是 a struct,并且无法序列化此结构的默认值。事实上,简单地做JsonSerializer.Serialize(new JsonElement());会抛出相同的异常(demo fiddle #2 here)。(这与JObjectwhich 是一个引用类型形成对比,其默认值当然是null。)
那么,您有哪些选择?您可以使所有JsonElement属性都可以为空,并IgnoreNullValues = true在重新序列化时进行设置:
public class JsonApiData
{
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("attributes")]
public JsonElement? Attributes { get; set; }
[JsonPropertyName("meta")]
public JsonElement? Meta { get; set; }
[JsonPropertyName("relationships")]
public JsonElement? Relationships { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
进而:
var reserialisedPayload = JsonSerializer.Serialize(payload, new JsonSerializerOptions { IgnoreNullValues = true });
Run Code Online (Sandbox Code Playgroud)
演示小提琴 #3在这里。
或者,在.NET 5 或更高版本中,您可以使用以下内容标记您的所有JsonElement属性[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]:
public class JsonApiData
{
// Remainder unchanged
[JsonPropertyName("attributes")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public JsonElement Attributes { get; set; }
[JsonPropertyName("meta")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public JsonElement Meta { get; set; }
[JsonPropertyName("relationships")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public JsonElement Relationships { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这样做将导致在序列化期间跳过未初始化的元素,而无需修改序列化选项。
演示小提琴 #4在这里。
或者,您可以通过绑定所有 JSON 属性而不是像这样Id的JsonExtensionData属性来简化数据模型:
public class JsonApiData
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这种方法避免了IgnoreNullValues重新序列化时需要手动设置,因此 ASP.NET Core 会自动正确地重新序列化模型。
演示小提琴 #5在这里。