【问题标题】:create objects from properties in string从字符串中的属性创建对象
【发布时间】:2016-01-30 20:08:04
【问题描述】:

应该创建具有类似 json 符号字符串的附加属性的对象。 方法将从 Razor 视图调用以将 colmodel 传递给 jqgrid 像json对象一样

@Html.Raw( Json.Encode( Model.GetColModel()))

方法应该有类似的签名

object GetColModel(string colName, int colWidth, string additonalProperties)

例如,

GetColModel("customer", 17, "address=\"Toronto\", index=1555" )

应该返回对象

new { colName="customer", colwidth=17, address="Toronto", index=1555 }

可能存在嵌套属性,例如 JSON,eq.

GetColModel("customer", 17, "formatoptions= new { formatter=\"number\", editable=true } " )

应该返回对象

new { colName="customer", colwidth=17, formatoptions=new {
                   formatter="number", 
                   editable=true
                   }
}

我试过方法

    public object GetColModel(string colName, int colWidth, string additonalProperties)
    {
        return new
        {
            name = colName,
            width = colWidth,
            &addtitionalProperties
        };
    }

但这失败了,因为 C# 不支持宏

如何创建这样的方法或其他方式将属性从数据库添加到 Razor 视图中的 json 字符串?

它是从 ASP.NET/Mono C# MVC 4 视图模型中调用的。 使用 Razor 视图和 RazorEngine。

【问题讨论】:

    标签: c# json asp.net-mvc razor expandoobject


    【解决方案1】:

    没有任何内置功能可以执行此操作,但是您可以使用 string 解析字符串(string.Split 将允许您在 ',' 上进行拆分,但如果您的文本中可能包含这些内容,则必须构建一个真正的解析器,或者将您的字符串格式切换为 CSV 之类的格式,在那里您可以找到很多解析器。您可能能够找到一个用于简单语法的属性解析器。或者您将附加属性字符串推送为 json 并使用 Json.net 进行解析。

    将字符串解析为键/值结构后,您可以使用 ExpandoObject 填充最终对象并将其返回。
    https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx

    【讨论】:

    • 我可以将附加属性作为 json 字符串传递,并使用 Json.Net 解析器从中创建 .NET 对象。如何将这些属性添加到返回的对象?是否有一些示例如何为此使用 expando 对象?
    • 没有具体的例子,但是Expando的重点是你可以动态添加属性。
    【解决方案2】:

    这是一个真正基于 json 的解决方案的简单实现。
    您可以使用以下方式调用它:

    dynamic d = Model.GetColModel("customer", 17, " { formatoptions : { formatter : \"number\", editable :true }, stam :2}");
    

    实施:

    static class ModelExtension
    {   
        public static dynamic GetColModel(this Model model, string colName, int colWidth, string additonalProperties) {
            dynamic expando = new ExpandoObject();
            var json = JsonConvert.DeserializeObject<JObject>(additonalProperties);
    
            expando.name = colName;
            expando.width = colWidth;
    
            return new FromPropertiesDynamicObjectCreator(expando, json);
        }
    
        private class FromPropertiesDynamicObjectCreator : DynamicObject
        {
            private readonly dynamic expando = null;
    
            public FromPropertiesDynamicObjectCreator(IDictionary<string, object> expando, JObject props = null) {
                this.expando = expando;
    
                if (props != null) {
                    ((dynamic)this).props = props;
                }
            }
    
            public override bool TrySetMember(SetMemberBinder binder, object value) {
                if (binder.Name.Equals("props")) {
                    var jsonObj = value as JObject;
                    JToken current = jsonObj.First;
                    var dictionary = expando as IDictionary<string, object>;
    
                    RecurseJson(current, dictionary);
                    return true;
                }
    
                return false;
            }
    
            private void RecurseJson(JToken current, IDictionary<string, object> dictionary) {
                JToken value;
                Dictionary<string, object> newDictionary;
    
                while (current != null) {
                    var children = current.Children().ToList();
    
                    foreach (var child in children) {
                        switch (child.Type) {
    
                            case JTokenType.Object:
                            case JTokenType.Array:
                                newDictionary = new Dictionary<string, object>();
                                dictionary[child.Path] = newDictionary;
                                RecurseJson(child, newDictionary);
                                break;
    
                            case JTokenType.Property:
                                var prop = ((JProperty)child);
                                value = prop.Value;
    
                                if (value.HasValues) {
                                    newDictionary = new Dictionary<string, object>();
                                    dictionary[prop.Name] = newDictionary;
                                    RecurseJson(child, newDictionary);
                                    break;
                                }
                                dictionary[prop.Name] = ((dynamic)value).Value;
                                break;
    
                            default:
                                var val = ((dynamic)child).Value;
    
                                if (val is JToken) {
                                    dictionary[child.Path] = val.Value;
                                }
                                else {
                                    dictionary[child.Path] = val;
                                }
    
                                break;
                        }
                    }
    
                    current = current.Next;
                }
            }
    
            public override bool TryGetMember(GetMemberBinder binder, out object result) {
                object value;
                var dictionary = expando as IDictionary<string, object>;
    
                if (dictionary.TryGetValue(binder.Name, out value)) {
                    var innerDictionary = value as IDictionary<string, object>;
    
                    if (innerDictionary != null) {
                        result = new FromPropertiesDynamicObjectCreator(innerDictionary);
                    }
                    else {
                        result = value;
                    }
                    return true;
                }
    
                result = null;
                return true;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多