[英]Serialize json to an object with catch all dictionary property
我想使用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可以反序列化為值為1 = 1,2 = 1的實例,TheRest = Dictionary {{“three,3}}
最簡單的方法是使用JsonExtensionData
屬性來定義catch all dictionary。
Json.Net文檔中的示例:
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
您可以創建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());
}
}
}
因此,在反序列化JSON字符串后,mappedObj的輸出將是一個對象, One
填充了One
和Two
屬性,並將其他所有內容放入Dictionary
。 當然,我將One和Two值硬編碼為int
,但我認為這證明了你如何去做。
我希望這有幫助。
編輯 :我更新了代碼,使其更通用。 我沒有完全測試它,所以在某些情況下它會失敗,但我認為它會讓你大部分時間都在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.