我想使用JSON.net反序列化为对象,但将未映射的属性放在字典属性中.可能吗?
比如给json,
{one:1,two:2,three:3}
Run Code Online (Sandbox Code Playgroud)
和c#类:
public class Mapped {
public int One {get; set;}
public int Two {get; set;}
public Dictionary<string,object> TheRest {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
JSON.NET可以反序列化为值为1 = 1,2 = 1的实例,TheRest = Dictionary {{"three,3}}
The easiest way to do this is to use the JsonExtensionData attribute to define a catch all dictionary.
Example from 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
Run Code Online (Sandbox Code Playgroud)
您可以创建一个CustomCreationConverter来执行您需要执行的操作。这是一个示例(相当丑陋,但演示了您可能想要如何实现这一点):
namespace JsonConverterTest1
{
public class Mapped
{
private Dictionary<string, object> _theRest = new Dictionary<string, object>();
public int One { get; set; }
public int Two { get; set; }
public Dictionary<string, object> TheRest { get { return _theRest; } }
}
public class MappedConverter : CustomCreationConverter<Mapped>
{
public override Mapped Create(Type objectType)
{
return new Mapped();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var mappedObj = new Mapped();
var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();
//return base.ReadJson(reader, objectType, existingValue, serializer);
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
string readerValue = reader.Value.ToString().ToLower();
if (reader.Read())
{
if (objProps.Contains(readerValue))
{
PropertyInfo pi = mappedObj.GetType().GetProperty(readerValue, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
var convertedValue = Convert.ChangeType(reader.Value, pi.PropertyType);
pi.SetValue(mappedObj, convertedValue, null);
}
else
{
mappedObj.TheRest.Add(readerValue, reader.Value);
}
}
}
}
return mappedObj;
}
}
public class Program
{
static void Main(string[] args)
{
string json = "{'one':1, 'two':2, 'three':3, 'four':4}";
Mapped mappedObj = JsonConvert.DeserializeObject<Mapped>(json, new MappedConverter());
Console.WriteLine(mappedObj.TheRest["three"].ToString());
Console.WriteLine(mappedObj.TheRest["four"].ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,反序列化 JSON 字符串后,mappedObj 的输出将是一个对象,其One和Two属性已填充,其他所有内容都放入Dictionary. 当然,我将“一”和“二”值硬编码为ints,但我认为这演示了您将如何处理此问题。
我希望这有帮助。
编辑:我更新了代码以使其更通用。我没有完全测试它,所以在某些情况下它可能会失败,但我认为它可以帮助您实现大部分目标。