首页 > 解决方案 > 将模型转换为动态,设置新属性并返回为 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 结束。

还有一点需要注意:我需要它用于可能返回大量此类元素的端点 - 它应该可能很快。

标签: c#.netcasting

解决方案


我找到了一些解决方案,但我不确定这是否是最好的:

 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);
 }

推荐阅读