【问题标题】:C# JsonConverter changing null to 0C# JsonConverter 将 null 更改为 0
【发布时间】:2020-11-11 00:26:08
【问题描述】:

我在 Newtonsoft.json 中使用 JsonConverters。他们将为我提供我将使用的自定义 WriteJson / ReadJson 代码,因此当给定的 objectType 与转换器匹配时,我需要同时触发 WriteJson / ReadJson。

我需要做的一件事是将 json 中显示的“null”关键字转换为 0。

下面是一个非常简化的 JsonConverter——它所做的只是尝试将“null”更改为 0(以及其他任何不为 null 的内容为 1)。不幸的是,我发现当 value == null 时,WriteJson 函数永远不会被触发。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;


namespace ConsoleApp1
{
  class Program
  {
    public class TestConverter : JsonConverter
    {
      public override bool CanConvert(Type objectType)
      {
        return objectType == typeof(B);
      }

      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
      {
        return existingValue;
      }

      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
      {
        /// This function never gets triggered when value is null
        if (value == null)
        {
          writer.WriteValue(0);
        }  
        else
        {
          writer.WriteValue(1);
        }
      }
    }

    public class B
    {
      public int C
      {
        get; set;
      }
    }

    public class A
    {
      public B B
      {
        get; set;
      } = null;
    }


    static void Main(string[] args)
    {
      var c = JsonConvert.SerializeObject(new A(), new JsonSerializerSettings()
      {
        Converters = new List<JsonConverter> { new TestConverter() }
      });

      Console.WriteLine(c);
    }
  }
}

输出:

{"B":null}

预期输出:

{"B": 0}

是否有一些设置或方法可以将“null”的所有输出转换为“0”?

【问题讨论】:

标签: c# serialization json.net


【解决方案1】:

示例中的转换器类仅在传递类型为“B”的对象时有效。因为在CanConvert 方法中,您正在检查对象是否为“B”类型。

public override bool CanConvert(Type objectType)
{
    return objectType == typeof(B);
}

您应该将typeof(B) 更改为typeof(A),因此转换器将转换您在示例代码中创建的“A”类:

var c = JsonConvert.SerializeObject(new A(), new JsonSerializerSettings()
{
    Converters = new List<JsonConverter> { new TestConverter() }
});

现在您正在检查“A”对象。要获取“A”中的“B”对象,需要将对象强制转换为“A”,然后可以判断“A”中的“B”对象是否为空。

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
   // cast object to A first, then get the B.
   B obj = ((A)value).B;

   // create our object first with WriteStartObject().
   writer.WriteStartObject();
   
   // write B's name in json, then it's value.
   writer.WritePropertyName(nameof(B));
   writer.WriteValue(obj != null ? 1 : 0); //ternary conditional that returns 0 for null, 1 for not-null.

   // end our object with WriteEndObject().
   writer.WriteEndObject();
}

因此,结果将如下所示:

{"B":0}

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 2020-04-07
    • 1970-01-01
    • 2019-10-03
    • 2020-03-24
    • 1970-01-01
    • 2015-01-26
    • 2019-08-23
    相关资源
    最近更新 更多