是的,这是可能的,但您确实需要一些自定义代码来执行此操作。
有点难看,但是你可以创建一个自定义的IDataContractSurrogate 类来将JSON 反序列化为Dictionary<string, Dictionary<string, object>>,然后将嵌套字典结构中的值复制到List<Thing> 中。这是代理所需的代码:
class MyDataContractSurrogate : IDataContractSurrogate
{
public Type GetDataContractType(Type type)
{
if (type == typeof(List<Thing>))
{
return typeof(Dictionary<string, Dictionary<string, object>>);
}
return type;
}
public object GetDeserializedObject(object obj, Type targetType)
{
if (obj.GetType() == typeof(Dictionary<string, Dictionary<string, object>>) &&
targetType == typeof(List<Thing>))
{
List<Thing> list = new List<Thing>();
foreach (var kvp in (Dictionary<string, Dictionary<string, object>>)obj)
{
Thing thing = new Thing { ThingName = kvp.Key };
Dictionary<string, object> propsDict = kvp.Value;
foreach (PropertyInfo prop in GetDataMemberProperties(typeof(Thing)))
{
DataMemberAttribute att = prop.GetCustomAttribute<DataMemberAttribute>();
object value;
if (propsDict.TryGetValue(att.Name, out value))
{
prop.SetValue(thing, value);
}
}
list.Add(thing);
}
return list;
}
return obj;
}
public object GetObjectToSerialize(object obj, Type targetType)
{
if (obj.GetType() == typeof(List<Thing>) &&
targetType == typeof(Dictionary<string, Dictionary<string, object>>))
{
var thingsDict = new Dictionary<string, Dictionary<string, object>>();
foreach (Thing thing in (List<Thing>)obj)
{
var propsDict = new Dictionary<string, object>();
foreach (PropertyInfo prop in GetDataMemberProperties(typeof(Thing)))
{
DataMemberAttribute att = prop.GetCustomAttribute<DataMemberAttribute>();
propsDict.Add(att.Name, prop.GetValue(thing));
}
thingsDict.Add(thing.ThingName, propsDict);
}
return thingsDict;
}
return obj;
}
private IEnumerable<PropertyInfo> GetDataMemberProperties(Type type)
{
return type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetCustomAttribute<DataMemberAttribute>() != null);
}
// ------- The rest of these methods are not needed -------
public object GetCustomDataToExport(Type clrType, Type dataContractType)
{
throw new NotImplementedException();
}
public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
{
throw new NotImplementedException();
}
public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection<Type> customDataTypes)
{
throw new NotImplementedException();
}
public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
{
throw new NotImplementedException();
}
public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
{
throw new NotImplementedException();
}
}
要使用代理,您需要创建DataContractJsonSerializerSettings 的实例并将其传递给DataContractJsonSerializer,并设置以下属性。请注意,由于我们需要 UseSimpleDictionaryFormat 设置,因此此解决方案仅适用于 .Net 4.5 或更高版本。
var settings = new DataContractJsonSerializerSettings();
settings.DataContractSurrogate = new MyDataContractSurrogate();
settings.KnownTypes = new List<Type> { typeof(Dictionary<string, Dictionary<string, object>>) };
settings.UseSimpleDictionaryFormat = true;
请注意,在您的Thing 类中,您不应使用[DataMember] 属性标记ThingName 成员,因为它是在代理中专门处理的。另外,我假设您的班级成员实际上是 properties(使用{ get; set; }),而不是您在问题中写的 fields。如果该假设不正确,您需要将代理代码中对PropertyInfo 的所有引用更改为使用FieldInfo;否则代理将不起作用。
[DataContract]
public class Thing
{
// Don't mark this property with [DataMember]
public string ThingName { get; set; }
[DataMember(Name = "property1")]
public int Property1 { get; set; }
[DataMember(Name = "property2")]
public string Property2 { get; set; }
}
这是一个往返演示:
public class Program
{
public static void Main(string[] args)
{
string json = @"
{
""thing_name1"": {
""property1"": 0,
""property2"": ""sure""
},
""thing_name2"": {
""property1"": 34,
""property2"": ""absolutely""
}
}";
var settings = new DataContractJsonSerializerSettings();
settings.DataContractSurrogate = new MyDataContractSurrogate();
settings.KnownTypes = new List<Type> { typeof(Dictionary<string, Dictionary<string, object>>) };
settings.UseSimpleDictionaryFormat = true;
List<Thing> things = Deserialize<List<Thing>>(json, settings);
foreach (Thing thing in things)
{
Console.WriteLine("ThingName: " + thing.ThingName);
Console.WriteLine("Property1: " + thing.Property1);
Console.WriteLine("Property2: " + thing.Property2);
Console.WriteLine();
}
json = Serialize(things, settings);
Console.WriteLine(json);
}
public static T Deserialize<T>(string json, DataContractJsonSerializerSettings settings)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(typeof(T), settings);
return (T)ser.ReadObject(ms);
}
}
public static string Serialize(object obj, DataContractJsonSerializerSettings settings)
{
using (MemoryStream ms = new MemoryStream())
{
var ser = new DataContractJsonSerializer(obj.GetType(), settings);
ser.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
输出:
ThingName: thing_name1
Property1: 0
Property2: sure
ThingName: thing_name2
Property1: 34
Property2: absolutely
{"thing_name1":{"property1":0,"property2":"sure"},"thing_name2":{"property1":34,"property2":"absolutely"}}