Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用C-NewtonSoft.Json进行条件序列化_C#_.net_Serialization_Json.net_Jsonserializer - Fatal编程技术网

C# 如何使用C-NewtonSoft.Json进行条件序列化

C# 如何使用C-NewtonSoft.Json进行条件序列化,c#,.net,serialization,json.net,jsonserializer,C#,.net,Serialization,Json.net,Jsonserializer,我正在使用NewtonSoft.json进行json序列化 public class CommonBase { [JsonProperty(PropertyName = "u_customer_id")] public long CustomerId { get; set; } } 我想进行条件序列化,这样,如果CustomerId值为0,我想在json序列化期间为CustomerId设置一个空值。因为CommonBase是一个基类,所以我无法将数据类型从long更改为stri

我正在使用NewtonSoft.json进行json序列化

public class CommonBase
{
    [JsonProperty(PropertyName = "u_customer_id")]
    public long CustomerId { get; set; }
}
我想进行条件序列化,这样,如果CustomerId值为0,我想在json序列化期间为CustomerId设置一个空值。因为CommonBase是一个基类,所以我无法将数据类型从long更改为string


我怎样才能做到这一点?

你的问题标题中几乎有答案。你要找的是

您只需要添加如下名称的方法:ShouldSerialize+PropertyName。在您的情况下,方法应该如下所示:

public bool ShouldSerializeCustomerId()
{
   return SomeCondition;
}

另外,如果要创建基类,可能需要使用抽象类。

我已通过将CustomerId属性更改为nullable解决了此问题

   public long? CustomerId { get; set; }

您可以编写自己的自定义序列化程序。这里的示例:。您需要实现WriteJson和ReadJsonmethods@xszaboj..i我只是在检查JSON.Net是否为此提供了任何内置功能或任何解决方法。您的预期结果是什么?u_customer_id:null或u_customer_id:或在序列化时跳过该属性?预期结果为u_customer_id:因此json属性有时为空时为字符串,有时为非空时为数字。这是一个非常糟糕的合同设计。谁对此负责?如果在所有情况下u_customer_id都是字符串,请检查合同描述