gpt4 book ai didi

c# - 使用捕获所有字典属性将 json 序列化为对象

转载 作者:太空狗 更新时间:2023-10-29 19:41:45 25 4
gpt4 key购买 nike

我想使用 JSON.net 反序列化为对象,但将未映射的属性放入字典属性中。可能吗?

例如给定json,

 {one:1,two:2,three:3}

和 c# 类:

public class Mapped {
public int One {get; set;}
public int Two {get; set;}
public Dictionary<string,object> TheRest {get; set;}
}

JSON.NET 能否反序列化为值为 one=1, two=1, TheRest= Dictionary{{"three,3}} 的实例

最佳答案

最简单的方法是使用 JsonExtensionData 属性定义一个 catch all 字典。

示例来自 the Json.Net documentation :

public class DirectoryAccount
{
// normal deserialization
public string DisplayName { get; set; }

// these properties are set in OnDeserialized
public string UserName { get; set; }
public string Domain { get; set; }

[JsonExtensionData]
private IDictionary<string, JToken> _additionalData;

[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// SAMAccountName is not deserialized to any property
// and so it is added to the extension data dictionary
string samAccountName = (string)_additionalData["SAMAccountName"];

Domain = samAccountName.Split('\\')[0];
UserName = samAccountName.Split('\\')[1];
}

public DirectoryAccount()
{
_additionalData = new Dictionary<string, JToken>();
}
}

string json = @"{
'DisplayName': 'John Smith',
'SAMAccountName': 'contoso\\johns'
}";

DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);

Console.WriteLine(account.DisplayName);
// John Smith

Console.WriteLine(account.Domain);
// contoso

Console.WriteLine(account.UserName);
// johns

关于c# - 使用捕获所有字典属性将 json 序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6829905/

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