c# - 将模型转换为动态,设置新属性并返回为 camelCased json
问题描述
我有一个模型类的对象。对于我的一个端点(多个),我需要附加到这个对象的附加属性,然后将所有的作为 camelCased JSON 返回。我的问题是这样的:
public class MyObject {
public string Property1{get;set;}
public string Property2{get;set;}
}
public IActionResult ReturnWithAdditionalProperty(MyObject myObject) {
var dynamizedObject = (dynamic)myObject;
dynamizedObject.NewProperty = true;
return Json(dynamizedObject)
}
设置 NewProperty 失败(模型仍显示为 MyObject 项)。
由于我不想将它添加到模型(此属性仅在一种情况下使用)或创建新模型(ia 由于大量属性),我只想使用新属性使其动态化,然后返回。
我该怎么做?目前我正在将 Json 序列化和反序列化作为动态的,但不幸的是,这以返回 PascalCase 变量名而不是 camelCase 结束。
还有一点需要注意:我需要它用于可能返回大量此类元素的端点 - 它应该可能很快。
解决方案
我找到了一些解决方案,但我不确定这是否是最好的:
public static class ExpandoConvert {
public static ExpandoObject ConvertToExpando(object obj) {
var expando = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expando;
foreach (var property in obj.GetType().GetProperties())
dictionary.Add(property.Name, property.GetValue(obj));
return expando;
}
}
并使用这个:
public IActionResult ReturnWithAdditionalProperty(MyObject myObject) {
var dynamizedObject = ExpandoConvert.ConvertToExpando(myObject);
dynamizedObject.NewProperty = true;
var jsonSerializerSettings = new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
return Json(query, jsonSerializerSettings);
}
推荐阅读
- ruby - 如何通过 Ruby Selenium Binding(或 WATIR)创建 chrome 配置文件
- python - 参数解析期间的Python断言错误
- ruby-on-rails - Rails mysql2 gem 错误
- java - SQL 查询的内部服务器错误
- pdf - gnuplot 自动调整大小 pdf
- c++ - C ++检查Web浏览器是否关闭
- android - 如何将位图从 Activity 传递给服务
- spring-boot - 如何找出正在运行的模式脚本 spring-boot?
- php - WordPress Metabox 不会保存
- python - 查找列表 1 中也存在于列表 2 中的项目