当前位置: 首页 > 工具软件 > DotLiquid > 使用案例 >

Dotliquid使用Json模板变量

汪飞捷
2023-12-01

Dotliquid是不错的Template Engine,为了更方便使用,扩展了一下,使它支持json数据的替换,引用了Newtonsoft.Json.Linq

/// <summary>
        /// 从JObject创建模板变量
        /// </summary>
        /// <param name="jsonObject"></param>
        /// <returns></returns>
        protected Hash FromJson(JObject jsonObject)
        {
            if (jsonObject == null) return null;
            var hash = new Hash();
            foreach (JProperty item in jsonObject.Children())
            {
                if (item.HasValues && item.Type == JTokenType.Property)
                {
                    switch (item.Value.Type)
                    {
                        case JTokenType.Object:
                            var jObj = item.Value as JObject;
                            if (jObj != null)
                                hash.Add(item.Name, FromJson(jObj));
                            break;
                        case JTokenType.Array:
                            var jArray = item.Value as JArray;
                            if (jArray != null)
                                hash.Add(item.Name, FromJson(jArray));
                            break;
                        case JTokenType.String:
                        case JTokenType.Integer:
                        case JTokenType.Date:
                        case JTokenType.Boolean:
                        case JTokenType.Float:
                        case JTokenType.Guid:
                        case JTokenType.TimeSpan:
                        case JTokenType.Uri:
                            JValue value = item.Value as JValue;
                            if (value != null)
                                hash.Add(item.Name, value.Value);
                            break;
                    }
                }
            }
            return hash;
        }
/// <summary>
        /// 从JArray创建模板变量
        /// </summary>
        /// <param name="jsonArray"></param>
        /// <returns></returns>
        protected List<Hash> FromJson(JArray jsonArray)
        {
            if (jsonArray == null) return null;
            var listHash = new List<Hash>();
            for (int i = 0; i < jsonArray.Count; i++)
            {
                var item = (JObject)jsonArray[i];
                var value = FromJson(item);
                if (value != null)
                {
                    listHash.Add(FromJson(item));
                }
            }
            return listHash;
        }

 

 

转载于:https://www.cnblogs.com/keo2013/p/3294543.html

 类似资料: