/// <summary> /// 将正文格式化为字节流 /// </summary> /// <param name="format"> 包含格式规范的格式字符串 </param> /// <param name="body"> 请求或响应正文 </param> /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param> /// <returns> </returns> public override byte[] Serialize(string format, IEnumerable <KeyValuePair <string, object> > body, IFormatProvider formatProvider) { string json; if (body == null) { json = "null"; } else if (body.FirstOrDefault().Key == null && body.Count() == 1) { json = ComponentServices.ToJsonString(body.FirstOrDefault().Value); } else if (body.GetType().GetInterfaces().Any(t => t == typeof(IDictionary) || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary <,>)))) { json = ComponentServices.ToJsonString(body); } else { json = ComponentServices.ToJsonString(new DictionaryWrapper(body)); } var charset = GetEncoding(formatProvider) ?? Encoding.UTF8; return(charset.GetBytes(json)); }
/// <summary> /// 返回指定类型的对象,其值等效于指定对象。 /// </summary> /// <param name="context"> </param> /// <param name="input"> 需要转换类型的对象 </param> /// <param name="outputType"> 换转后的类型 </param> /// <param name="success"> 是否成功 </param> protected override string ChangeType(ConvertContext context, object input, Type outputType, out bool success) { success = true; if (input is DataRow || input is DataRowView) { return(ComponentServices.ToJsonString(input)); } var reader = input as IDataReader; if (reader != null) { if (reader.IsClosed) { success = false; context.AddException("DataReader已经关闭"); return(null); } switch (reader.FieldCount) { case 0: return(null); case 1: return(BaseChangeType(context, reader.GetValue(0), outputType, out success)); default: return(ComponentServices.ToJsonString(input)); } } if (input.IsNull()) { return(null); } if (input is bool) { return((bool)input ? "true" : "false"); } var convertible = input as IConvertible; if (convertible != null) { return(convertible.ToString(null)); } var formattable = input as IFormattable; if (formattable != null) { return(formattable.ToString(null, null)); } var type = input as Type; if (type != null) { return(CType.GetFriendlyName(type)); } var bs = input as byte[]; if (bs != null) { return(Encoding.UTF8.GetString(bs)); } var ps = input.GetType().GetProperties(); if (ps.Length > 0) { return(ComponentServices.ToJsonString(input)); } return(input.ToString()); }
public override string ToString() { return(ComponentServices.ToJsonString(this)); }