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