JsonMapper.cs 18 KB

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