我有以下类:
public class MainClass
{
public static MainClass[] array = new MainClass[1]
{
new MainClass
{
subClass = new SubClass[2]
{
new SubClass
{
variable1 = "my value"
},
new SubClass
{
variable1 = "my value"
}
}
}
};
public SubClass[] subClass;
[DataContract]
public class SubClass
{
public string variable1 = "default value";
[DataMember] // because only variable2 should be saved in json
public string variable2 = "default value";
}
}
保存如下:
File.WriteAllText("data.txt", JsonConvert.SerializeObject(new
{
MainClass.array
}, new JsonSerializerSettings { Formatting = Formatting.Indented }));
data.txt:
{
"array": [
{
"subClass": [
{
"variable2": "value from json"
},
{
"variable2": "value from json"
}
]
}
]
}
然后我反序列化并像这样填充我的对象:
JObject json = JObject.Parse(File.ReadAllText("data.txt"));
if (json["array"] != null)
{
for (int i = 0, len = json["array"].Count(); i < len; i++)
{
using (var sr = json["array"][i].CreateReader())
{
JsonSerializer.CreateDefault().Populate(sr, MainClass.array[i]);
}
}
}
但是,当我打印以下变量时:
Console.WriteLine(MainClass.array[0].subClass[0].variable1);
Console.WriteLine(MainClass.array[0].subClass[0].variable2);
Console.WriteLine(MainClass.array[0].subClass[1].variable1);
Console.WriteLine(MainClass.array[0].subClass[1].variable2);
则输出为:
default value
value from json
default value
value from json
而不是"默认值",应该有"我的值",因为这是我在创建类的实例时使用的,JsonSerializer应该只用json的值填充对象。
如何正确地填充整个对象,而不重置json中不包含的属性?
看起来好像JsonSerializer.Populate()
缺少JObject.Merge()
可用的MergeArrayHandling
设置。通过测试,我发现:
-
填充数组或其他类型的只读集合的成员似乎像
MergeArrayHandling.Replace
一样工作。这是你正在经历的行为——现有的数组和其中的所有项都被丢弃,并被一个包含新构造的具有默认值的项的新数组所取代。相反,您需要
MergeArrayHandling.Merge
: 将数组项合并在一起,由索引匹配。 -
填充像
List<T>
这样的读写集合的成员似乎和MergeArrayHandling.Concat
一样工作
请求Populate()
支持此设置的增强似乎是合理的——尽管我不知道实现它有多容易。至少Populate()
的文档应该解释这个行为。
同时,这里有一个自定义的JsonConverter
,它具有必要的逻辑来模拟MergeArrayHandling.Merge
的行为:
public class ArrayMergeConverter<T> : ArrayMergeConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsArray && objectType.GetArrayRank() == 1 && objectType.GetElementType() == typeof(T);
}
}
public class ArrayMergeConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (!objectType.IsArray)
throw new JsonSerializationException(string.Format("Non-array type {0} not supported.", objectType));
var contract = (JsonArrayContract)serializer.ContractResolver.ResolveContract(objectType);
if (contract.IsMultidimensionalArray)
throw new JsonSerializationException("Multidimensional arrays not supported.");
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.StartArray)
throw new JsonSerializationException(string.Format("Invalid start token: {0}", reader.TokenType));
var itemType = contract.CollectionItemType;
var existingList = existingValue as IList;
IList list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
case JsonToken.Null:
list.Add(null);
break;
case JsonToken.EndArray:
var array = Array.CreateInstance(itemType, list.Count);
list.CopyTo(array, 0);
return array;
default:
// Add item to list
var existingItem = existingList != null && list.Count < existingList.Count ? existingList[list.Count] : null;
if (existingItem == null)
{
existingItem = serializer.Deserialize(reader, itemType);
}
else
{
serializer.Populate(reader, existingItem);
}
list.Add(existingItem);
break;
}
}
// Should not come here.
throw new JsonSerializationException("Unclosed array at path: " + reader.Path);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
}
然后将转换器添加到subClass
成员中,如下所示:
[JsonConverter(typeof(ArrayMergeConverter))]
public SubClass[] subClass;
或者,如果你不想添加Json。. NET属性添加到数据模型中,可以在序列化器设置中添加它:
var settings = new JsonSerializerSettings
{
Converters = new[] { new ArrayMergeConverter<MainClass.SubClass>() },
};
JsonSerializer.CreateDefault(settings).Populate(sr, MainClass.array[i]);
这个转换器是专门为数组设计的,但是类似的转换器也可以很容易地为读写集合(如List<T>
)创建。