JsonMapper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using PTMedicalInsurance.Common;
  4. using PTMedicalInsurance.Variables;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Reflection;
  9. namespace PTMedicalInsurance.Helper
  10. {
  11. /// <summary>
  12. /// 将json转换为实体对象
  13. /// </summary>
  14. public class JsonMapper
  15. {
  16. const string ArrayPattern = "[]";
  17. private string jsonConfig;
  18. private string configFile;
  19. private JsonMappingSetting setting;
  20. public JsonMapper(string name)
  21. {
  22. configFile = Global.curEvt.path + "/config/" + name + ".json";
  23. reload();
  24. }
  25. public void reload()
  26. {
  27. try
  28. {
  29. // 加载字段映射配置
  30. if (File.Exists(configFile))
  31. {
  32. jsonConfig = File.ReadAllText(configFile);
  33. setting = JsonHelper.toObject<JsonMappingSetting>(JObject.Parse(jsonConfig));
  34. }
  35. else
  36. {
  37. setting = new JsonMappingSetting();
  38. }
  39. }
  40. catch (Exception ex)
  41. {
  42. throw new Exception("配置文件异常:"+ex.Message);
  43. }
  44. }
  45. /// <summary>
  46. /// 获取入参映射
  47. /// </summary>
  48. /// <returns></returns>
  49. public List<FieldMapping> GetInputMapping()
  50. {
  51. return setting.Input??new List<FieldMapping>();
  52. }
  53. /// <summary>
  54. /// 设置入参
  55. /// </summary>
  56. /// <param name="value"></param>
  57. public void SetInputMapping(List<FieldMapping> value)
  58. {
  59. setting.Input = value;
  60. }
  61. /// <summary>
  62. /// 获取出参映射
  63. /// </summary>
  64. /// <returns></returns>
  65. public List<FieldMapping> GetOutputMapping()
  66. {
  67. return setting.Output ?? new List<FieldMapping>();
  68. }
  69. /// <summary>
  70. /// 设置出参
  71. /// </summary>
  72. /// <param name="value"></param>
  73. public void SetOutputMapping(List<FieldMapping> value)
  74. {
  75. setting.Output = value;
  76. }
  77. /// <summary>
  78. /// 获取转换类
  79. /// </summary>
  80. /// <returns></returns>
  81. private ConvertMapping GetConverter()
  82. {
  83. return setting.Convert??new ConvertMapping();
  84. }
  85. /// <summary>
  86. /// 根据实体类获取Json
  87. /// </summary>
  88. /// <param name="typeName"></param>
  89. /// <returns></returns>
  90. private string GetConvertJson(string typeName)
  91. {
  92. if (!string.IsNullOrEmpty(typeName))
  93. {
  94. if (typeName.IndexOf(".")<1)
  95. {
  96. typeName = "PTMedicalInsurance.Entity.Local." + typeName;
  97. }
  98. Type type = Type.GetType(typeName);
  99. if (type != null)
  100. {
  101. Object obj = Activator.CreateInstance(type);
  102. return JsonHelper.toJsonString(obj, false);
  103. }
  104. }
  105. return string.Empty;
  106. }
  107. /// <summary>
  108. /// 将参数方向对调
  109. /// </summary>
  110. public void ChangeDirection(List<FieldMapping> mappings)
  111. {
  112. mappings.ForEach((map) =>
  113. {
  114. if (!string.IsNullOrEmpty(map.Source) && !string.IsNullOrEmpty(map.Target))
  115. {
  116. string orgin = map.Target;
  117. map.Target = map.Source;
  118. map.Source = orgin;
  119. }
  120. });
  121. }
  122. /// <summary>
  123. /// 入参实例JSON
  124. /// </summary>
  125. /// <returns></returns>
  126. public string GetInputJson()
  127. {
  128. return GetConvertJson(GetConverter()?.Input);
  129. }
  130. /// <summary>
  131. /// 出参实例JSON
  132. /// </summary>
  133. /// <returns></returns>
  134. public string GetOutputJson()
  135. {
  136. return GetConvertJson(GetConverter()?.Output);
  137. }
  138. /// <summary>
  139. /// Json字段映射
  140. /// </summary>
  141. /// <param name="jObject"></param>
  142. /// <returns></returns>
  143. private JObject MapJson(string key,JObject jSource)
  144. {
  145. JObject jObject = new JObject();
  146. if(string.IsNullOrEmpty(jsonConfig) || string.IsNullOrEmpty(key))
  147. {
  148. return jSource;
  149. }
  150. List<FieldMapping> fieldMappings = "input".Equals(key) ? GetInputMapping() : GetOutputMapping() ;
  151. if (fieldMappings != null)
  152. {
  153. // 对于每一个字段映射信息
  154. foreach (var fieldMapping in fieldMappings)
  155. {
  156. if (!string.IsNullOrEmpty(fieldMapping.Target))
  157. {
  158. // 单一映射或一对多统一处理
  159. string[] targets = fieldMapping.Target.Split(",".ToCharArray());
  160. List<FieldMapping> fields = new List<FieldMapping>();
  161. foreach (var t in targets)
  162. {
  163. fields.Add(new FieldMapping()
  164. {
  165. Source = fieldMapping.Source,
  166. Expression = fieldMapping.Expression,
  167. Target = t,
  168. Value = fieldMapping.Value,
  169. Child = fieldMapping.Child
  170. }) ;
  171. }
  172. fields.ForEach((f) =>
  173. {
  174. MapItem(f,jSource,jObject);
  175. });
  176. }
  177. else
  178. {
  179. MapItem(fieldMapping, jSource, jObject);
  180. }
  181. }
  182. }
  183. return jObject;
  184. }
  185. private void MapItem(FieldMapping fieldMapping, JObject jSource, JObject jObject)
  186. {
  187. // 使用JToken.SelectToken来获取源路径对应的值
  188. dynamic value = new JValue("");
  189. string nameKey = fieldMapping.Source;
  190. string expression = fieldMapping.Expression;
  191. if (!string.IsNullOrEmpty(nameKey) && string.IsNullOrEmpty(fieldMapping.Value))
  192. {
  193. nameKey = nameKey.Split(",".ToCharArray())[0]; //多对一忽略后面的
  194. if (fieldMapping.Child != null)
  195. {
  196. //数组映射
  197. nameKey = nameKey.Replace(ArrayPattern, "");
  198. }
  199. else
  200. {
  201. if (nameKey.Contains(ArrayPattern))
  202. {
  203. //数组映射对象时,取第一个
  204. nameKey = nameKey.Replace(ArrayPattern, "[0]");
  205. }
  206. }
  207. value = jSource.SelectToken(nameKey);
  208. }
  209. else if (fieldMapping.Value != null)
  210. {
  211. // 支持固定值
  212. value = new JValue(fieldMapping.Value);
  213. }
  214. // 表达式(全局变量)
  215. if ((expression ?? "").Equals("GlobaVariables"))
  216. {
  217. value = GetExpressionValue(expression, fieldMapping.Source);
  218. expression = null;
  219. }
  220. // 表达式(扩展字段)
  221. if ((expression ?? "").Equals("SaveToExpand"))
  222. {
  223. SetExpression(expression, fieldMapping.Source, value);
  224. return;
  225. }
  226. string converter = "ShortDate,NoSplitDate,ConvertToString";
  227. if (expression!=null && converter.IndexOf(expression)!=-1)
  228. {
  229. value = GetExpressionValue(expression, value);
  230. expression = null;
  231. }
  232. // 普通转换
  233. if (value != null)
  234. {
  235. if (fieldMapping.Child != null)
  236. {
  237. Type type = value.GetType();
  238. var items = new JArray();
  239. //如果为JValue,则为一对多(忽略此时的name)
  240. if (type == typeof(JValue))
  241. {
  242. JObject sub = new JObject();
  243. // 此时只返回一条数据的集合
  244. fieldMapping.Child.ForEach((c) =>
  245. {
  246. MapItem(c, jSource, sub);
  247. });
  248. items.Add(sub);
  249. }
  250. else if (type == typeof(JArray))
  251. {
  252. //数组映射,此时的value为array
  253. foreach (var item in (JArray)value)
  254. {
  255. var child = MapChildItem((JObject)item, fieldMapping.Child);
  256. items.Add(child);
  257. }
  258. }
  259. CreateJObjectFromString(jObject, fieldMapping.Target.Replace(ArrayPattern, ""), items, 0);
  260. }
  261. else
  262. {
  263. ParseAndMap(value, jObject, nameKey, fieldMapping.Target, expression);
  264. }
  265. }
  266. }
  267. /// <summary>
  268. /// 映射子对象
  269. /// </summary>
  270. /// <param name="itemObject"></param>
  271. /// <param name="childs"></param>
  272. /// <returns></returns>
  273. private JObject MapChildItem(JObject itemObject, List<FieldMapping> childs)
  274. {
  275. JObject newItem = new JObject();
  276. foreach (FieldMapping subMapping in childs)
  277. {
  278. if (subMapping.Value != null)
  279. {
  280. newItem[subMapping.Target] = subMapping.Value;
  281. }
  282. else
  283. {
  284. newItem[subMapping.Target] = itemObject[subMapping.Source];
  285. }
  286. }
  287. return newItem;
  288. }
  289. /// <summary>
  290. /// 映射实体
  291. /// </summary>
  292. /// <typeparam name="TSource">源对象</typeparam>
  293. /// <typeparam name="TTarget">目标对象</typeparam>
  294. /// <param name="name">名称</param>
  295. /// <param name="sourceItem">源数据</param>
  296. /// <returns></returns>
  297. public TTarget Map<TSource, TTarget>(string key, TSource sourceItem)
  298. {
  299. var json = JsonConvert.SerializeObject(sourceItem);
  300. var jObject = JObject.Parse(json);
  301. // 映射
  302. JObject jRet = MapJson(key,jObject);
  303. // 然后将修改后的JObject再转化到目标类型的对象
  304. var targetItem = jRet.ToObject<TTarget>();
  305. return targetItem;
  306. }
  307. /// <summary>
  308. /// 解析对象后转换为JObject
  309. /// </summary>
  310. /// <typeparam name="TSource"></typeparam>
  311. /// <typeparam name="TTarget"></typeparam>
  312. /// <param name="sourceItem"></param>
  313. /// <returns></returns>
  314. //[Obsolete("建议使用Map方法")]
  315. private JObject MapObject<TSource, TTarget>(string key,TSource sourceItem)
  316. {
  317. TTarget target = Map<TSource, TTarget>(key,sourceItem);
  318. var json = JsonConvert.SerializeObject(target);
  319. return JObject.Parse(json);
  320. }
  321. /// <summary>
  322. /// 入参映射
  323. /// </summary>
  324. /// <typeparam name="TSource"></typeparam>
  325. /// <typeparam name="TTarget"></typeparam>
  326. /// <param name="sourceItem"></param>
  327. /// <returns></returns>
  328. public JObject MapRequest<TSource, TTarget>(TSource sourceItem)
  329. {
  330. Global.writeLog("1.3.1");
  331. TTarget target = Map<TSource, TTarget>("input",sourceItem);
  332. Global.writeLog("1.3.2");
  333. var json = JsonConvert.SerializeObject(target);
  334. return JObject.Parse(json);
  335. }
  336. /// <summary>
  337. /// 出参映射
  338. /// </summary>
  339. /// <typeparam name="TSource"></typeparam>
  340. /// <typeparam name="TTarget"></typeparam>
  341. /// <param name="sourceItem"></param>
  342. /// <returns></returns>
  343. public JObject MapResponse<TSource, TTarget>(TSource sourceItem)
  344. {
  345. TTarget target = Map<TSource, TTarget>("output", sourceItem);
  346. var json = JsonConvert.SerializeObject(target);
  347. return JObject.Parse(json);
  348. }
  349. /// <summary>
  350. /// 解析并映射字段
  351. /// </summary>
  352. /// <param name="sourceToken"></param>
  353. /// <param name="targetObject"></param>
  354. /// <param name="sourcePath"></param>
  355. /// <param name="targetPath"></param>
  356. private void ParseAndMap(JToken sourceToken, JObject targetObject, string sourcePath, string targetPath, string expression = "")
  357. {
  358. // 支持映射多个字段
  359. var targetFields = targetPath.Split(',');
  360. foreach (var targetField in targetFields) {
  361. //if (!sourceToken.HasValues && string.IsNullOrEmpty(sourceToken.Value<string>())) continue;
  362. ParseAndMapField(sourceToken, targetObject, sourcePath, targetField, expression);
  363. }
  364. }
  365. /// <summary>
  366. /// 解析并映射单个字段
  367. /// </summary>
  368. /// <param name="sourceToken"></param>
  369. /// <param name="targetObject"></param>
  370. /// <param name="sourcePath"></param>
  371. /// <param name="targetPath"></param>
  372. private void ParseAndMapField(JToken value, JObject targetObject, string sourcePath, string targetPath, string expression = "")
  373. {
  374. if (string.IsNullOrEmpty(targetPath)) return;
  375. if (sourcePath !=null && sourcePath.StartsWith(".")) { sourcePath = sourcePath.Substring(1); }
  376. if (targetPath.StartsWith(".")) { targetPath = targetPath.Substring(1); }
  377. var targetTokens = targetPath.Split('.');
  378. var remainingTargetPath = string.Join(".", targetTokens, 0, targetTokens.Length - 1);
  379. var isArray = remainingTargetPath.Contains(ArrayPattern);
  380. var remainingTargetTokens = remainingTargetPath.Split(ArrayPattern.ToCharArray());
  381. //var value = sourceToken.SelectToken(sourcePath);
  382. // 抵达路径顶点
  383. if (targetTokens.Length == 1)
  384. {
  385. targetObject.Add(targetTokens[0], value);
  386. return;
  387. }
  388. // 处理数组类型的映射
  389. if (isArray)
  390. {
  391. if (value is JValue) {
  392. // 将固定数据给数组中的第一个对象
  393. var newItem = (targetObject[targetTokens[0]] ?? new JObject()) as JObject;
  394. CreateJObjectFromString(newItem, targetPath, (JValue)value,1,expression);
  395. targetObject[targetTokens[0]] = newItem;
  396. }
  397. //if (value is JArray)
  398. //{
  399. // string[] childPath = sourcePath.Split(ArrayPattern.ToCharArray());
  400. // string[] destPath = targetPath.Split(ArrayPattern.ToCharArray());
  401. // string arrayKey = targetTokens[0].Split(ArrayPattern.ToCharArray())[0];
  402. // var newItem = (targetObject[arrayKey] ?? new JArray()) as JArray;
  403. // //CreateJObjectFromString(newItem, targetPath, null,0);
  404. // foreach (var item in ((JArray)value).Children<JObject>())
  405. // {
  406. // var childItem = new JObject();
  407. // ParseAndMapField(item.SelectToken(childPath[2].Substring(1)), childItem, childPath[2], destPath[2]); // 递归处理嵌套路径
  408. // newItem.Add(childItem);
  409. // }
  410. // targetObject[arrayKey] = newItem;
  411. //}
  412. }
  413. else if (targetTokens.Length > 1) {
  414. // 对象层级
  415. string nameKey = targetTokens[0];
  416. int index = 1; //不包含根节点
  417. if (nameKey.Contains("[]"))
  418. {
  419. nameKey = nameKey.Substring(0, nameKey.Length - 2);
  420. index = 0;
  421. }
  422. var newItem = (targetObject[nameKey] ?? new JObject()) as JObject;
  423. CreateJObjectFromString(newItem,targetPath,(JValue)value, index, expression);
  424. targetObject[nameKey] = newItem;
  425. }
  426. else // 普通嵌套映射
  427. {
  428. var newItem = new JObject();
  429. ParseAndMapField(value, newItem, sourcePath, remainingTargetPath); // 递归处理嵌套路径
  430. targetObject.Add(targetTokens[0], newItem);
  431. }
  432. targetObject.Remove(sourcePath);
  433. }
  434. /// <summary>
  435. /// 根据层级创建对象
  436. /// </summary>
  437. /// <param name="current"></param>
  438. /// <param name="input"></param>
  439. /// <param name="value"></param>
  440. /// <returns></returns>
  441. private JObject CreateJObjectFromString(JObject current, string input,JToken value,int index = 1,string expression = "")
  442. {
  443. var keys = input.Split('.');
  444. JObject root = current;
  445. for (int i = index; i < keys.Length - 1; i++)
  446. {
  447. if (keys[i].EndsWith("[]"))
  448. {
  449. string actualKey = keys[i].Substring(0, keys[i].Length - 2);
  450. if (current[actualKey] == null)
  451. {
  452. current[actualKey] = new JArray { new JObject() };
  453. }
  454. // 数组的某一条
  455. current = (JObject)((JArray)current[actualKey]).Last; ;
  456. }
  457. else
  458. {
  459. if (current[keys[i]] == null)
  460. {
  461. current[keys[i]] = new JObject();
  462. }
  463. current = (JObject)current[keys[i]];
  464. }
  465. }
  466. if (!string.IsNullOrEmpty(expression)) {
  467. value = GetExpressionValue(expression, value);
  468. }
  469. current[keys[keys.Length - 1]] = value;
  470. return root;
  471. }
  472. private void SetExpression(string method, string key,object value)
  473. {
  474. try
  475. {
  476. Type type = typeof(ExpressionEvaluator);
  477. MethodInfo mi = type.GetMethod(method);
  478. if (mi != null)
  479. {
  480. mi.Invoke(null, new object[] {key,value });
  481. }
  482. }
  483. catch (Exception e)
  484. { }
  485. }
  486. private string GetExpressionValue(string method,object value)
  487. {
  488. object objRtn = null;
  489. try
  490. {
  491. Type type = typeof(ExpressionEvaluator);
  492. MethodInfo mi = type.GetMethod(method);
  493. if (mi != null)
  494. {
  495. objRtn = mi.Invoke(null, new object[] { value });
  496. }
  497. }
  498. catch (Exception e)
  499. { }
  500. return objRtn?.ToString();
  501. }
  502. /// <summary>
  503. /// 保存配置
  504. /// </summary>
  505. public void Save()
  506. {
  507. jsonConfig = JsonHelper.toJsonString(this.setting);
  508. if(!string.IsNullOrEmpty(jsonConfig) && !string.IsNullOrEmpty(configFile))
  509. {
  510. File.WriteAllText(configFile,jsonConfig);
  511. }
  512. }
  513. }
  514. public class JsonMappingSetting
  515. {
  516. public List<FieldMapping> Input { set; get; }
  517. public List<FieldMapping> Output { set; get; }
  518. public ConvertMapping Convert { set; get; }
  519. }
  520. public class FieldMapping
  521. {
  522. public string Source { get; set; }
  523. public string Target { get; set; }
  524. public string Value { get; set; }
  525. public string Expression { set; get; }
  526. public string Name { get; set; }
  527. public List<FieldMapping> Child { get; set; }
  528. public FieldMapping()
  529. { }
  530. }
  531. public class ConvertMapping
  532. {
  533. public string Input { set; get; }
  534. public string Output { set; get; }
  535. }
  536. }