gpt4 book ai didi

.net - 使用 .Net 反序列化 JSON 中的动态类型

转载 作者:行者123 更新时间:2023-12-01 10:07:47 26 4
gpt4 key购买 nike

我有以下 JSON:

\"success\":true,
\"requestSecs\":0.084988117218,
\"body\":{
\"countsByStatus\":[
{
\"status\":\"yes\",
\"counts\":{
\"byType\":{
\"fulltime\":0,
\"parttime\":0,
\"sub\":0,
},
\"total\":0
}
}

我使用以下类将其反序列化为.net:
[DataContract]
public class ResponseAttendanceList
{
[DataMember(Name = "success")]
public string Success;

[DataMember(Name = "requestSecs")]
public string RequestSecs;

[DataMember(Name = "body")]
public AttendanceList AttendanceList;
}

[DataContract]
public class AttendanceList
{
[DataMember(Name = "countsByStatus")]
public List<Status> countsByStatus;
}

[DataContract]
public class Status
{
[DataMember(Name = "status")]
public string status;

[DataMember(Name = "counts")]
public Counts counts;
}

[DataContract]
public class Counts
{
[DataMember(Name = "byType")]
public ByType byType;

}

[DataContract]
public class ByType
{
[DataMember(Name = "fulltime")]
public int fulltime;

[DataMember(Name = "parttime")]
public int parttime;

[DataMember(Name = "sub")]
public int sub;
}

问题是,反序列化为 ByType 类的类型实际上是动态的,因此可以更改。如何在不知道类型(全职、兼职、子)的情况下反序列化此 JSON。我试图在“计数”类上这样做,但没有奏效:
    [DataContract]
public class Counts
{
[DataMember(Name = "byType")]
public KeyValuePair<string, int> byType;
}

最佳答案

查看这个答案,链接到的讨论符合您的需要。关键是新的dynamic类型:

Deserialize JSON into C# dynamic object?

关于.net - 使用 .Net 反序列化 JSON 中的动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5507540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com