我有一个DTO类,我序列化
Json.Serialize(MyClass)
我如何排除该物业的公共财产?
(它必须是公共的,因为我在其他地方的代码中使用它)
我有一个DTO类,我序列化
Json.Serialize(MyClass)
我如何排除该物业的公共财产?
(它必须是公共的,因为我在其他地方的代码中使用它)
当前回答
你可以使用[ScriptIgnore]:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > 0 && !string.IsNullOrEmpty(Name); }
}
}
在这种情况下,Id和名称只会被序列化
其他回答
您也可以使用[NonSerialized]属性
[Serializable]
public struct MySerializableStruct
{
[NonSerialized]
public string hiddenField;
public string normalField;
}
来自微软文档:
指示可序列化类的字段不应被序列化。这个类不能被继承。
例如,如果你使用Unity(这不仅仅适用于Unity),那么这适用于UnityEngine。JsonUtility
using UnityEngine;
MySerializableStruct mss = new MySerializableStruct
{
hiddenField = "foo",
normalField = "bar"
};
Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}
如果你使用Json。Net属性[JsonIgnore]将在序列化或反序列化时简单地忽略字段/属性。
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
或者你可以使用DataContract和DataMember属性来有选择地序列化/反序列化属性/字段。
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
详情请参阅http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size
如果你在。net框架中使用System.Web.Script.Serialization,你可以把ScriptIgnore属性放在不应该被序列化的成员上。请看下面的例子:
考虑以下(简化)情况: 公共类用户{ 公共int Id{获取;设置;} 公共字符串名称{获取;设置;} (ScriptIgnore) public bool IsComplete { string.IsNullOrEmpty(Name);} } } 在这种情况下,只有Id和Name属性会被序列化,因此生成的JSON对象看起来像这样: {Id: 3,名称:'测试用户'}
另外,不要忘记添加对“System.Web”的引用。扩展”
为dotnet核心添加System.Text.Json版本
对于编译时,根据上面的答案添加[JsonIgnore]。
对于运行时,需要将JsonConverter添加到选项中。
首先,为要排除的类型创建一个JsonConverter,例如下面的ICollection<LabMethod>
public class LabMethodConverter : JsonConverter<ICollection<LabMethod>>
{
public override ICollection<LabMethod> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
//deserialize JSON into a ICollection<LabMethod>
return null;
}
public override void Write(Utf8JsonWriter writer, ICollection<LabMethod> value, JsonSerializerOptions options)
{
//serialize a ICollection<LabMethod> object
writer.WriteNullValue();
}
}
然后在序列化Json时添加到选项
var options = new JsonSerializerOptions();
options.Converters.Add(new LabMethodConverter());
var new_obj = Json(new { rows = slice, total = count }, options);
对于c# 9的记录,它是[property: JsonIgnore]
using System.Text.Json.Serialization;
public record R(
string Text2
[property: JsonIgnore] string Text2)
对于经典样式,它仍然只是[JsonIgnore]。
using System.Text.Json.Serialization;
public record R
{
public string Text {get; init; }
[JsonIgnore]
public string Text2 { get; init; }
}