Json.net 仅序列化某些属性

Cur*_*per 9 c# serialization attributes json.net

Json.net 有没有办法只指定要序列化的属性?或者根据绑定标志(如仅声明)序列化某些属性?

现在我正在使用JObject.FromObject(MainObj.SubObj);获取 SubObj 的所有属性,它是一个遵循 ISubObject 接口的类的实例:

public interface ISubObject
{

}

public class ParentSubObject : ISubObject
{
    public string A { get; set; }
}


public class SubObjectWithOnlyDeclared : ParentSubObject
{
    [JsonInclude] // This is fake, but what I am wishing existed
    public string B { get; set; }

    [JsonInclude] // This is fake, but what I am wishing existed
    public string C { get; set; }
}

public class NormalSubObject: ParentSubObject
{
    public string B { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果MainObj.SubObj是 aNormalSubObject它会同时对 A 和 B 进行序列化,但如果是SubObjectWithOnlyDeclared它只会对 B 和 C 进行序列化并忽略父属性

Alf*_*fie 26

[JsonIgnore]不是必须按照另一个答案中的建议对您不想序列化的每个属性使用。

如果您只想指定要序列化的属性,则可以使用[JsonObject(MemberSerialization.OptIn)][JsonProperty]属性来执行此操作,如下所示:

using Newtonsoft.Json;
...
[JsonObject(MemberSerialization.OptIn)]
public class Class1
{
    [JsonProperty]
    public string Property1 { set; get; }
    public string Property2 { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

这里只会Property1连载。

  • 这应该是选定的答案 (2认同)

Ese*_*ser 9

您可以编写如下所示的自定义 ContractResolver

public class IgnoreParentPropertiesResolver : DefaultContractResolver
{
    bool IgnoreBase = false;
    public IgnoreParentPropertiesResolver(bool ignoreBase)
    {
        IgnoreBase = ignoreBase;
    }
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var allProps = base.CreateProperties(type, memberSerialization);
        if (!IgnoreBase) return allProps;

        //Choose the properties you want to serialize/deserialize
        var props = type.GetProperties(~BindingFlags.FlattenHierarchy); 

        return allProps.Where(p => props.Any(a => a.Name == p.PropertyName)).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在序列化过程中使用它:

var settings = new JsonSerializerSettings() { 
                      ContractResolver = new IgnoreParentPropertiesResolver(true) 
               };
var json1 = JsonConvert.SerializeObject(new SubObjectWithOnlyDeclared(),settings );
Run Code Online (Sandbox Code Playgroud)