Program.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // See https://aka.ms/new-console-template for more information
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using OrBit.MESInterface.OrderVerifyWebService.Application;
  5. string aaa = "{\r\n \"Code\": 200,\r\n \"Data\": [\r\n {\r\n \"ID\": \"1002311180000366\",\r\n \"DocNo\": \"HBRC231100035\"\r\n }\r\n ],\r\n \"Msg\": \"\"\r\n}";
  6. AnalyticResult analyticResult = new AnalyticResult();
  7. var jobj = DeserializeStringToObject(aaa);
  8. analyticResult.data = jobj;
  9. var jstr = JsonConvert.SerializeObject(analyticResult);
  10. Console.WriteLine(jstr);
  11. /// <summary>
  12. /// 将json字符串反序列化为字典类型
  13. /// </summary>
  14. /// <typeparam name="TKey">字典key</typeparam>
  15. /// <typeparam name="TValue">字典value</typeparam>
  16. /// <param name="jsonStr">json字符串</param>
  17. /// <returns>字典数据</returns>
  18. static Dictionary<string, object> DeserializeStringToDictionary(string jsonStr)
  19. {
  20. if (string.IsNullOrEmpty(jsonStr))
  21. return new Dictionary<string, object>();
  22. Dictionary<string, object> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonStr);
  23. return jsonDict;
  24. }
  25. /// <summary>
  26. /// 根据json字符串类型将json字符串反序列化为字典或者集合类型
  27. /// </summary>
  28. /// <param name="jsonStr"></param>
  29. /// <returns></returns>
  30. static object DeserializeStringToObject(string jsonStr)
  31. {
  32. if (isJArray(jsonStr))
  33. {
  34. return JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonStr);
  35. }
  36. return DeserializeStringToDictionary(jsonStr);
  37. }
  38. static bool isJArray(string json)
  39. {
  40. if (string.IsNullOrEmpty(json))
  41. {
  42. return false;
  43. }
  44. try
  45. {
  46. JArray.Parse(json);
  47. return true;
  48. }
  49. catch
  50. {
  51. return false;
  52. }
  53. }