我想用JSON反序列化一个对象,但把未映射特性在字典属性。这可能吗?
I would like to use JSON to deserialize to an object but put unmapped properties in a dictionary property. Is it possible?
例如给出的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,TheRest =字典{{三,3}}
Can JSON.NET deserialize to an instance with values one=1, two=1, TheRest= Dictionary{{"three,3}}
推荐答案您可以创建一个的 CustomCreationConverter 做你需要做的事情。下面是一个示例(比较难看,但是它展示了你可能会想怎么去这个):
You can create a CustomCreationConverter to do what you need to do. Here's a sample (rather ugly, but demonstrates how you may want to go about this):
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()); } } }
所以mappedObj后输出你反序列化JSON字符串将与它的一和两个属性填充,以及其他一切投入词典。当然,我硬编码了一,二值 INT S,但我认为这证明了你会如何去这一点。
So the output of mappedObj after you deserialize the JSON string will be an object with its One and Two properties populated, and everything else put into the Dictionary. Granted, I hard-coded the One and Two values as ints, but I think this demonstrates how you'd go about this.
我希望这有助于
修改:我更新了代码,使其更通用。我没有完全测试它,所以有可能某些情况下,它失败了,但我认为它可以让你最成名的途径。
EDIT: I updated the code to make it more generic. I didn't fully test it out, so there may some cases where it fails, but I think it gets you most of the way there.
更多推荐
JSON序列化与包罗万象的词典属性的对象
发布评论