JsonMapper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. TTarget target = Map<TSource, TTarget>("input",sourceItem);
  331. var json = JsonConvert.SerializeObject(target);
  332. return JObject.Parse(json);
  333. }
  334. /// <summary>
  335. /// 出参映射
  336. /// </summary>
  337. /// <typeparam name="TSource"></typeparam>
  338. /// <typeparam name="TTarget"></typeparam>
  339. /// <param name="sourceItem"></param>
  340. /// <returns></returns>
  341. public JObject MapResponse<TSource, TTarget>(TSource sourceItem)
  342. {
  343. TTarget target = Map<TSource, TTarget>("output", sourceItem);
  344. var json = JsonConvert.SerializeObject(target);
  345. return JObject.Parse(json);
  346. }
  347. /// <summary>
  348. /// 解析并映射字段
  349. /// </summary>
  350. /// <param name="sourceToken"></param>
  351. /// <param name="targetObject"></param>
  352. /// <param name="sourcePath"></param>
  353. /// <param name="targetPath"></param>
  354. private void ParseAndMap(JToken sourceToken, JObject targetObject, string sourcePath, string targetPath, string expression = "")
  355. {
  356. // 支持映射多个字段
  357. var targetFields = targetPath.Split(',');
  358. foreach (var targetField in targetFields) {
  359. //if (!sourceToken.HasValues && string.IsNullOrEmpty(sourceToken.Value<string>())) continue;
  360. ParseAndMapField(sourceToken, targetObject, sourcePath, targetField, expression);
  361. }
  362. }
  363. /// <summary>
  364. /// 解析并映射单个字段
  365. /// </summary>
  366. /// <param name="sourceToken"></param>
  367. /// <param name="targetObject"></param>
  368. /// <param name="sourcePath"></param>
  369. /// <param name="targetPath"></param>
  370. private void ParseAndMapField(JToken value, JObject targetObject, string sourcePath, string targetPath, string expression = "")
  371. {
  372. if (string.IsNullOrEmpty(targetPath)) return;
  373. if (sourcePath !=null && sourcePath.StartsWith(".")) { sourcePath = sourcePath.Substring(1); }
  374. if (targetPath.StartsWith(".")) { targetPath = targetPath.Substring(1); }
  375. var targetTokens = targetPath.Split('.');
  376. var remainingTargetPath = string.Join(".", targetTokens, 0, targetTokens.Length - 1);
  377. var isArray = remainingTargetPath.Contains(ArrayPattern);
  378. var remainingTargetTokens = remainingTargetPath.Split(ArrayPattern.ToCharArray());
  379. //var value = sourceToken.SelectToken(sourcePath);
  380. // 抵达路径顶点
  381. if (targetTokens.Length == 1)
  382. {
  383. targetObject.Add(targetTokens[0], value);
  384. return;
  385. }
  386. // 处理数组类型的映射
  387. if (isArray)
  388. {
  389. if (value is JValue) {
  390. // 将固定数据给数组中的第一个对象
  391. var newItem = (targetObject[targetTokens[0]] ?? new JObject()) as JObject;
  392. CreateJObjectFromString(newItem, targetPath, (JValue)value,1,expression);
  393. targetObject[targetTokens[0]] = newItem;
  394. }
  395. //if (value is JArray)
  396. //{
  397. // string[] childPath = sourcePath.Split(ArrayPattern.ToCharArray());
  398. // string[] destPath = targetPath.Split(ArrayPattern.ToCharArray());
  399. // string arrayKey = targetTokens[0].Split(ArrayPattern.ToCharArray())[0];
  400. // var newItem = (targetObject[arrayKey] ?? new JArray()) as JArray;
  401. // //CreateJObjectFromString(newItem, targetPath, null,0);
  402. // foreach (var item in ((JArray)value).Children<JObject>())
  403. // {
  404. // var childItem = new JObject();
  405. // ParseAndMapField(item.SelectToken(childPath[2].Substring(1)), childItem, childPath[2], destPath[2]); // 递归处理嵌套路径
  406. // newItem.Add(childItem);
  407. // }
  408. // targetObject[arrayKey] = newItem;
  409. //}
  410. }
  411. else if (targetTokens.Length > 1) {
  412. // 对象层级
  413. string nameKey = targetTokens[0];
  414. int index = 1; //不包含根节点
  415. if (nameKey.Contains("[]"))
  416. {
  417. nameKey = nameKey.Substring(0, nameKey.Length - 2);
  418. index = 0;
  419. }
  420. var newItem = (targetObject[nameKey] ?? new JObject()) as JObject;
  421. CreateJObjectFromString(newItem,targetPath,(JValue)value, index, expression);
  422. targetObject[nameKey] = newItem;
  423. }
  424. else // 普通嵌套映射
  425. {
  426. var newItem = new JObject();
  427. ParseAndMapField(value, newItem, sourcePath, remainingTargetPath); // 递归处理嵌套路径
  428. targetObject.Add(targetTokens[0], newItem);
  429. }
  430. targetObject.Remove(sourcePath);
  431. }
  432. /// <summary>
  433. /// 根据层级创建对象
  434. /// </summary>
  435. /// <param name="current"></param>
  436. /// <param name="input"></param>
  437. /// <param name="value"></param>
  438. /// <returns></returns>
  439. private JObject CreateJObjectFromString(JObject current, string input,JToken value,int index = 1,string expression = "")
  440. {
  441. var keys = input.Split('.');
  442. JObject root = current;
  443. for (int i = index; i < keys.Length - 1; i++)
  444. {
  445. if (keys[i].EndsWith("[]"))
  446. {
  447. string actualKey = keys[i].Substring(0, keys[i].Length - 2);
  448. if (current[actualKey] == null)
  449. {
  450. current[actualKey] = new JArray { new JObject() };
  451. }
  452. // 数组的某一条
  453. current = (JObject)((JArray)current[actualKey]).Last; ;
  454. }
  455. else
  456. {
  457. if (current[keys[i]] == null)
  458. {
  459. current[keys[i]] = new JObject();
  460. }
  461. current = (JObject)current[keys[i]];
  462. }
  463. }
  464. if (!string.IsNullOrEmpty(expression)) {
  465. value = GetExpressionValue(expression, value);
  466. }
  467. current[keys[keys.Length - 1]] = value;
  468. return root;
  469. }
  470. private void SetExpression(string method, string key,object value)
  471. {
  472. try
  473. {
  474. Type type = typeof(ExpressionEvaluator);
  475. MethodInfo mi = type.GetMethod(method);
  476. if (mi != null)
  477. {
  478. mi.Invoke(null, new object[] {key,value });
  479. }
  480. }
  481. catch (Exception e)
  482. { }
  483. }
  484. private string GetExpressionValue(string method,object value)
  485. {
  486. object objRtn = null;
  487. try
  488. {
  489. Type type = typeof(ExpressionEvaluator);
  490. MethodInfo mi = type.GetMethod(method);
  491. if (mi != null)
  492. {
  493. objRtn = mi.Invoke(null, new object[] { value });
  494. }
  495. }
  496. catch (Exception e)
  497. { }
  498. return objRtn?.ToString();
  499. }
  500. /// <summary>
  501. /// 保存配置
  502. /// </summary>
  503. public void Save()
  504. {
  505. jsonConfig = JsonHelper.toJsonString(this.setting);
  506. if(!string.IsNullOrEmpty(jsonConfig) && !string.IsNullOrEmpty(configFile))
  507. {
  508. File.WriteAllText(configFile,jsonConfig);
  509. }
  510. }
  511. }
  512. public class JsonMappingSetting
  513. {
  514. public List<FieldMapping> Input { set; get; }
  515. public List<FieldMapping> Output { set; get; }
  516. public ConvertMapping Convert { set; get; }
  517. }
  518. public class FieldMapping
  519. {
  520. public string Source { get; set; }
  521. public string Target { get; set; }
  522. public string Value { get; set; }
  523. public string Expression { set; get; }
  524. public string Name { get; set; }
  525. public List<FieldMapping> Child { get; set; }
  526. public FieldMapping()
  527. { }
  528. }
  529. public class ConvertMapping
  530. {
  531. public string Input { set; get; }
  532. public string Output { set; get; }
  533. }
  534. }