Skip to content

Commit

Permalink
584:优化Json与Xml互转机制(2019-04-29)
Browse files Browse the repository at this point in the history
  • Loading branch information
cyq1162 committed Apr 30, 2019
1 parent 1e5dfa3 commit 7c980ee
Show file tree
Hide file tree
Showing 8 changed files with 249 additions and 84 deletions.
7 changes: 4 additions & 3 deletions Log/LogType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ internal static class Error
/// <param name="msg"></param>
internal static object Throw(string msg)
{
//#if DEBUG
// return "";
#if DEBUG
// return msg;
//#else
#endif
throw new Exception("V" + AppConfig.Version + " " + msg);
//#endif

}
}
/// <summary>
Expand Down
4 changes: 4 additions & 0 deletions Orm/SimpleOrmBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,10 @@ protected void SetInit(Object entityInstance, string tableName, string conn, Aop
/// </summary>
private void SetDelayInit(Object entityInstance, string tableName, string conn, AopOp op)
{
if(tableName==AppConfig.Log.LogTableName && string.IsNullOrEmpty(AppConfig.Log.LogConn))
{
return;
}
//if (string.IsNullOrEmpty(conn))
//{
// //不设置链接,则忽略(当成普通的实体类)
Expand Down
25 changes: 18 additions & 7 deletions SQL/Schema/TableSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -554,8 +554,15 @@ private static void SetStruct(MDataColumn mdc, PropertyInfo pi, FieldInfo fi, in
Type type = pi != null ? pi.PropertyType : fi.FieldType;
string name = pi != null ? pi.Name : fi.Name;
SqlDbType sqlType = SQL.DataType.GetSqlType(type);
JsonIgnoreAttribute jia = GetAttr<JsonIgnoreAttribute>(pi, fi);//获取Json忽略标识
if (jia != null)
{
return;//被Json忽略的列,不在返回列结构中。
}

mdc.Add(name, sqlType);
MCellStruct column = mdc[i];
MCellStruct column = mdc[mdc.Count - 1];

LengthAttribute la = GetAttr<LengthAttribute>(pi, fi);//获取长度设置
if (la != null)
{
Expand Down Expand Up @@ -604,16 +611,20 @@ private static void SetStruct(MDataColumn mdc, PropertyInfo pi, FieldInfo fi, in
{
column.Description = da.Description;
}
JsonIgnoreAttribute jia = GetAttr<JsonIgnoreAttribute>(pi, fi);//获取Json忽略标识
if (jia != null)
{
column.IsJsonIgnore = true;
}

}
private static T GetAttr<T>(PropertyInfo pi, FieldInfo fi)
{
Type type = typeof(T);
object[] attr = ReflectTool.GetAttributes(pi != null ? pi.PropertyType : fi.FieldType, typeof(T));// pi.GetCustomAttributes(type, false) : fi.GetCustomAttributes(type, false);//看是否设置了特性
object[] attr = null;
if (pi != null)
{
attr = ReflectTool.GetAttributes(pi, type);
}
else
{
attr = ReflectTool.GetAttributes(fi, type);
}

if (attr != null && attr.Length == 1)
{
Expand Down
67 changes: 34 additions & 33 deletions Table/MDataRow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1426,7 +1426,7 @@ internal object GetObj(Type toType, object objValue)
switch (sysType)
{
case SysType.Enum:
returnObj = Enum.Parse(propType, value);
returnObj = ConvertTool.ChangeType(objValue, toType);// Enum.Parse(propType, value);
break;
case SysType.Base:
#region 基础类型处理
Expand Down Expand Up @@ -1463,41 +1463,42 @@ internal object GetObj(Type toType, object objValue)
if (len == 1) // Table
{

if (JsonSplit.IsJson(value) && value.Contains(":") && value.Contains("{"))
if (value.Contains(":") && value.Contains("{"))
{
#region Json 嵌套处理,复杂数组处理。
MDataTable dt = MDataTable.CreateFrom(value);//, SchemaCreate.GetColumns(argTypes[0])
returnObj = Activator.CreateInstance(propType, dt.Rows.Count);//创建实例
Type objListType = returnObj.GetType();
bool isArray = sysType == SysType.Array;
for (int i = 0; i < dt.Rows.Count; i++)
{
MDataRow rowItem = dt.Rows[i];
object o = GetValue(rowItem, argTypes[0]);
MethodInfo method;
if (isArray)
{
Type objType = propType.Assembly.GetType(propType.FullName.Replace("[]", ""));
Object item = rowItem.ToEntity(objType);
method = objListType.GetMethod("Set");
if (method != null)
{
method.Invoke(returnObj, new object[] { i, item });
}
}
else
{
method = objListType.GetMethod("Add");
if (method == null)
{
method = objListType.GetMethod("Push");
}
if (method != null)
{
method.Invoke(returnObj, new object[] { o });
}
}
}
returnObj = dt.ToList(propType);
//returnObj = Activator.CreateInstance(propType, dt.Rows.Count);//创建实例
//Type objListType = returnObj.GetType();
//bool isArray = sysType == SysType.Array;
//for (int i = 0; i < dt.Rows.Count; i++)
//{
// MDataRow rowItem = dt.Rows[i];
// object o = GetValue(rowItem, argTypes[0]);
// MethodInfo method;
// if (isArray)
// {
// Type objType = propType.Assembly.GetType(propType.FullName.Replace("[]", ""));
// Object item = rowItem.ToEntity(objType);
// method = objListType.GetMethod("Set");
// if (method != null)
// {
// method.Invoke(returnObj, new object[] { i, item });
// }
// }
// else
// {
// method = objListType.GetMethod("Add");
// if (method == null)
// {
// method = objListType.GetMethod("Push");
// }
// if (method != null)
// {
// method.Invoke(returnObj, new object[] { o });
// }
// }
//}
dt = null;
#endregion
}
Expand Down
55 changes: 41 additions & 14 deletions Tool/JsonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using CYQ.Data.SQL;
using System.IO;
using System.Reflection;
using CYQ.Data.Xml;


namespace CYQ.Data.Tool
Expand Down Expand Up @@ -237,7 +238,7 @@ public void Add(string name, object value)
if (t.IsEnum)
{
value = (int)value;
Add(name, value.ToString(),true);
Add(name, value.ToString(), true);
}
else
{
Expand Down Expand Up @@ -1384,6 +1385,10 @@ public static string ToJson(object obj, bool isConvertNameToLower, RowOp rowOp,
return text;
}
}
else if (text[0] == '<' && text[text.Length - 1] == '>')
{
return XmlToJson(text, true);
}

JsonHelper js = new JsonHelper();
js.LoopCheckList.Add(obj.GetHashCode(), 0);
Expand All @@ -1397,30 +1402,31 @@ public static string ToJson(object obj, bool isConvertNameToLower, RowOp rowOp,


#region Xml 转 Json
/*

/// <summary>
/// 转Json
/// <param name="xml">xml字符串</param>
/// <param name="isConvertNameToLower">字段是否转小写</param>
/// <param name="isWithAttr">是否将属性值也输出</param>
/// </summary>
public static string ToJson(string xml, bool isConvertNameToLower, bool isWithAttr)
private static string XmlToJson(string xml, bool isWithAttr)
{
using (XHtmlAction action = new XHtmlAction(false, true))
{
try
{
action.LoadXml(xml);
return ToJson(action.XmlDoc.DocumentElement, isConvertNameToLower, isWithAttr);
return action.ToJson(action.XmlDoc.DocumentElement, isWithAttr);
}
catch (Exception err)
{
Log.Write(err, LogType.Error);
Log.WriteLogToTxt(err, LogType.Error);
return string.Empty;
}

}
}
*/
}

#endregion


Expand All @@ -1438,10 +1444,18 @@ public static string ToXml(string json, bool isWithAttr)
{
return ToXml(json, isWithAttr, DefaultEscape);
}
public static string ToXml(string json, bool isWithAttr, EscapeOp op)
{
return ToXml(json, isWithAttr, op, null);
}
/// <param name="isWithAttr">default value is true
/// <para>是否转成属性,默认true</para></param>
public static string ToXml(string json, bool isWithAttr, EscapeOp op)
public static string ToXml(string json, bool isWithAttr, EscapeOp op, string rootName)
{
if (!string.IsNullOrEmpty(rootName))
{
json = string.Format("{{\"{0}\":{1}}}", rootName, json);
}
StringBuilder xml = new StringBuilder();
xml.Append("<?xml version=\"1.0\" standalone=\"yes\"?>");
List<Dictionary<string, string>> dicList = JsonSplit.Split(json);
Expand All @@ -1450,14 +1464,14 @@ public static string ToXml(string json, bool isWithAttr, EscapeOp op)
bool addRoot = dicList.Count > 1 || dicList[0].Count > 1;
if (addRoot)
{
xml.Append("<root>");//</root>";
xml.Append(string.Format("<{0}>", rootName ?? "root"));//</root>";
}

xml.Append(GetXmlList(dicList, isWithAttr, op));

if (addRoot)
{
xml.Append("</root>");//</root>";
xml.Append(string.Format("</{0}>", rootName ?? "root"));//</root>";
}

}
Expand Down Expand Up @@ -1491,6 +1505,12 @@ private static string GetXml(Dictionary<string, string> dic, bool isWithAttr, Es
}
else
{
string key = item.Key;
if (key.EndsWith("List") && isWithAttr)
{
xml.AppendFormat("<{0}>", key);
key = key.Substring(0, key.Length - 4);
}
List<Dictionary<string, string>> jsonList = JsonSplit.Split(item.Value);
if (jsonList != null && jsonList.Count > 0)
{
Expand All @@ -1502,7 +1522,7 @@ private static string GetXml(Dictionary<string, string> dic, bool isWithAttr, Es
{
if (isWithAttr)
{
xml.Append(GetXmlElement(item.Key, jsonList[j], op));
xml.Append(GetXmlElement(key, jsonList[j], op));
}
else
{
Expand All @@ -1511,12 +1531,17 @@ private static string GetXml(Dictionary<string, string> dic, bool isWithAttr, Es
}
if (!isWithAttr)
{
xml.AppendFormat("</{0}>", item.Key);
xml.AppendFormat("</{0}>", key);
}
}
else // 空Json {}
{
xml.AppendFormat("<{0}></{0}>", item.Key);
xml.AppendFormat("<{0}></{0}>", key);
}

if (item.Key.EndsWith("List") && isWithAttr)
{
xml.AppendFormat("</{0}>", item.Key);
}
}
}
Expand All @@ -1530,7 +1555,9 @@ private static string GetXmlElement(string parentName, Dictionary<string, string
xml.Append("<" + parentName);
foreach (KeyValuePair<string, string> kv in dic)
{
if (kv.Value.IndexOf('"') > -1 || IsJson(kv.Value)) // 属性不能带双引号,所以转到元素处理。
if (kv.Value.IndexOf('"') > -1 || kv.Value.Length > 50
|| kv.Key.Contains("Remark") || kv.Key.Contains("Description") || kv.Key.Contains("Rule")
|| IsJson(kv.Value)) // 属性不能带双引号,所以转到元素处理。
{
jsonDic.Add(kv.Key, kv.Value);
}
Expand Down
Loading

0 comments on commit 7c980ee

Please sign in to comment.