- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有以下类(class):
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 }));
数据.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()
缺少 MergeArrayHandling
适用于 JObject.Merge()
的设置.通过测试我发现:
填充数组成员或某些其他类型的只读集合似乎像 MergeArrayHandling.Replace
一样工作.
这就是您遇到的行为——现有数组和其中的所有项都被丢弃并替换为包含具有默认值的新建项的新数组。相反,您需要 MergeArrayHandling.Merge
: 将数组项合并在一起,按索引匹配。
填充作为读/写集合的成员,例如 List<T>
看起来像 MergeArrayHandling.Concat
.
似乎合理request an enhancement那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>
.
关于c# - JsonSerializer.CreateDefault().Populate(..) 重置我的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422136/
我在 MongoDb 上有具有以下结构的文档, 我正在将 Mongoose 版本 ^4.8.1 与我的 Node 应用程序一起使用。我为上述文档创建了 3 个模式模型,如下所示, Event.js v
选择查询在 waterline-postgresql 的 .populate() 中不起作用。 Model.find(query).populate(assoc.alias,{select:['fie
我正在创建三个下拉菜单,它工作得很好,但我希望第二个下拉列表出现在第一个的选择上,第三个出现在第二个的选择上如何如果有人可以指导我或给我一个例子,我将不胜感激 PS:第二个下拉列表或表有一个来自第一个
我正在尝试使用 Show 模型中的数据填充()我的 User 模型中的所有订阅。我已经尝试过 .populate('subscriptions.show') 但它对结果没有任何作用。 如果我将订阅设置
我有一个集合,它有一个引用另一个集合的 objectId 的属性。 placeSchema = mongoose.Schema({ name: String, category: [{
我有一个像这样的 Mongoose 模式: var Address = { doorNo:String, city:String, state:String, coun
我有以下带有选择多个属性的下拉菜单,我需要将它们转换为普通下拉菜单,保持其功能: 从此: 对此: 以下是带有绑定(bind)的选择下拉列表: 下拉列表最初是从 foreach
我在 Kotlin 上使用 MongoDB 和 Spring,我希望我的应用程序在启动时填充 MongoDB 集合。 (并在每次启动时清洁它) 我的问题是,如果我正在填充的某些数据有问题,我该如何一一
org.apache.commons.beanutils.BeanUtils: BeanUtils.populate(Object bean, Map properties); Populate th
目前,我正在尝试使用一副纸牌填充 ArrayList,通过使用 for 循环来获取每张纸牌。它并没有完全按照我的预期工作,我希望有人能为我指明正确的方向。 我看到以下错误: System.Argume
我正在使用 MongooseDeepPopulate项目的包。我有 SchemaA、SchemaB、SchemaC、SchemaD。我的 SchemaD、SchemaC 连接到 SchemaB,而 S
我正在尝试更好地掌握 Express.js,并尝试创建一个简单的博客网站。 我的用户模型很简单:用户名、显示名称和一系列帖子。 const userSchema = new Schema({
我尝试了几种不同的方法,但我就是无法让 Mongoose 将 Users 信息填充到 Items 集合中。 文件:users.js var mongoose = require( 'mongoose'
我正在为 Spring Batch 作业编写集成测试。我想在每次测试之前使用存储库填充器将测试数据加载到内存数据库中。 到目前为止,我找到的示例似乎表明存储库填充器只会在上下文初始化时填充一次。这对我
这个问题已经有答案了: Get multiple elements by Id (15 个回答) 已关闭 8 年前。 我的网站中有 2 个下拉菜单,一个适用于用户使用手机时,另一个适用于用户使用桌面时
我正在使用 swift 构建一个 iPhone 应用程序,并且我有一个矩形横幅广告,我正试图展示它。我已经为 iAds 正确设置了我的 Dev 帐户,但广告没有填充到应用程序中。我得到了一个测试广告,
我想用指定的用户查询图像表,但我的代码不起作用。 Image.find().populate('user', { id : '1' }).sort({ updatedAt: 'desc' }).exe
所以我有我的改革对象,我想在验证之前解析我的字符串数据,以便能够使用干式验证 需要(:我的字段)。填充(GT?:0) 为了做到这一点,我使用 populator 属性:membership_fee,填
我有一个程序已经运行良好几个月了。今天早上我一直在尝试在服务器上安装 Postfix,突然网站上出现错误。这是回溯 mod_wsgi (pid=11948): Target WSGI script '
我使用函数.populate() 来获取按类别 分组的equipements,所以我的模型是这样的 var mongoose = require('../config/db'); var Equipe
我是一名优秀的程序员,十分优秀!