在JSON反序列化期间,可为空的Guid为空

本文关键字:Guid 为空 JSON 反序列化 | 更新日期: 2023-09-27 18:01:33

更新:在下面答案的帮助下,我能够看到我的代码中的错误并解决问题。

我想弄清楚为什么GUID?在反序列化期间被设置为null。我第一次看到这是在WebApi的POST中将parentStepId设置为null时。我验证了JSON在客户端有正确的parentStepId值。为了帮助找到问题所在,我创建了一个JsonConverter。在JsonConverter中,我可以看到JSON在转换之前具有正确的值,但转换后parentStepId被设置为null,即使它在JSON中具有有效的GUID

那么是什么导致了这个问题,或者我该如何解决这个问题?

在Ajax调用之前的客户端和JsonConverter中,JSON看起来像:
{
  "parentStepId": "c9ddfd7e-d124-e511-922d-ecf4bb4dc732",
  "workflowStep": {
    "enabled": true,
    "title": "9",
    "persistent": true,
    "extendable": false,
    "id": "00000000-0000-0000-0000-000000000000",
    "removeThisEntity": false,
    "deleteThisEntity": false,
    "serializeForServer": true
  },
  "order": 1,
  "id": "00000000-0000-0000-0000-000000000000",
  "removeThisEntity": false,
  "deleteThisEntity": false,
  "serializeForServer": true
}

下面是转换器的ReadJson:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);
        //parentStepId is the expected value here
        var tmpVal = jObject == null ? string.Empty : jObject.ToString();
        //parentStepId is set to null during this deserialization.
        var res = JsonConvert.DeserializeObject<OrderedWorkflow_WorkflowStep>(tmpVal);
        return res;
    }

OrderedWorkflow_WorkflowStep类:

public class OrderedWorkflow_WorkflowStep : TbdOrderedEntity
{
    public Guid? ParentWorkflowId { get; set; }
    public virtual WorkflowStep WorkflowStep { get; set; }
    public Guid? WorkflowStepId { get; set; }
}

在JSON反序列化期间,可为空的Guid为空

这个类没有正确映射所提供的JSON。

JSON - JSON中没有workflowStepId(或parentWorkflowId)。Net不知道如何映射字段,因此属性将保留其默认值。如果它们是不可空的,那么它们将是全为零的guid。

各种注释可以应用基本的转换——比如使用不同的字段名,可能应该分别是idparentStepId。例如:

public class OrderedWorkflow_WorkflowStep : TbdOrderedEntity
{
    [JsonProperty("parentStepId")]
    public Guid? ParentWorkflowId { get; set; }
    public virtual WorkflowStep WorkflowStep { get; set; }
    [JsonProperty("id")]    
    public Guid? WorkflowStepId { get; set; }
}