且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在模型中读取接口?

更新时间:2023-12-02 19:16:04

假设您控制Json,下面是一个有效的示例:我对类结构做了一些更改.

Assuming you control the Json, here's a working example: I've changed the class structure a bit.

它使用 TypeNameHandling.All 将类型信息写入Json-$type-,因此在反序列化(使用相同设置)时,它可以恢复类型.

It uses TypeNameHandling.All which writes the type information into the Json - as $type -, so when it's deserialized (using the same setting), it can restore the type.

void Main() {
    var crowd = new Crowd {
        People = new List<IPeople> {
            new Staff {
                PopupText = new List<PopupTextData> {
                new PopupTextData { DisplayName = "Staff"}
            }},
            new Spectator {
                PopupText = new List<PopupTextData> {
                new PopupTextData { DisplayName = "Spectator"}
            }},
        }
    };

    var settings = new JsonSerializerSettings {
        TypeNameHandling = TypeNameHandling.All,
        TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
    };

    var json = JsonConvert.SerializeObject(crowd, settings);

    var newCrowd = JsonConvert.DeserializeObject<ICrowd>(json, settings);
    Console.WriteLine(newCrowd.People.Count); // outputs '2'


}

public interface ICrowd {
    IList<IPeople> People { get; set; }
}

public interface IPeople {
    IList<PopupTextData> PopupText { get; set; }
}

public class Crowd : ICrowd {
    public IList<IPeople> People { get; set; }
}

public class Staff : IPeople {
    public IList<PopupTextData> PopupText { get; set; }
}

public class Spectator : IPeople {
    public IList<PopupTextData> PopupText { get; set; }
}

public class PopupTextData {
    public string DisplayName { get; set; }
    public string PopupValue { get; set; }
    public bool IsSeperator { get; set; }
}