using System; using System.Collections.Generic; using System.Text; using Jd.Api.Util; namespace Jd.Api { /// /// 符合Jd习惯的纯字符串字典结构。 /// public class JdDictionary : Dictionary { public JdDictionary() { } public JdDictionary(IDictionary dictionary) : base(dictionary) { } /// /// 添加一个新的键值对。空键或者空值的键值对将会被忽略。 /// /// 键名称 /// 键对应的值,目前支持:string, int, long, double, bool, DateTime类型 public void Add(string key, object value) { string strValue; if (value == null) { strValue = null; } else if (value is string) { strValue = (string)value; } else if (value is DateTime) { strValue = JdUtils.FormatDateTime((DateTime)value); } else if (value is Boolean) { strValue = ((Boolean)value).ToString().ToLower(); } else if (value is Nullable) { Nullable dateTime = value as Nullable; strValue = dateTime.HasValue ? JdUtils.FormatDateTime(dateTime.Value) : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString() : null; } else if (value is Nullable) { Nullable v = value as Nullable; strValue = v.HasValue ? v.Value.ToString().ToLower() : null; } else if (value is List) { List v = value as List; strValue = ParseFieldList(v); } else if (value is Byte[]) { strValue = Convert.ToBase64String((Byte[])value); } else { strValue = value.ToString(); } this.Add(key, strValue); } public new void AddNotNull(string key, string value) { if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { base.Add(key, value); } } public new void Add(string key, string value) { if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { base.Add(key, value); } } private String ParseFieldList(List list) { list.Sort((Jd.Api.Request.Field a, Jd.Api.Request.Field b) => { return String.Compare(a.Key, b.Key); }); IEnumerator enumerator = list.GetEnumerator(); StringBuilder query = new StringBuilder("["); Boolean first = true; while (enumerator.MoveNext()) { string key = enumerator.Current.Key; string value = enumerator.Current.Value; if (!string.IsNullOrEmpty(key)) { if (!first) query.Append(","); query.AppendFormat("{{\"{0}\":\"{1}\"}}", key, value); first = false; } } query.Append("]"); return query.ToString(); } } }