LitJsonHelper.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using LitJson;
  2. using System.Collections.Generic;
  3. namespace Common
  4. {
  5. public class LitJsonHelper
  6. {
  7. /// <summary>
  8. /// 递归遍历 LitJson 的任意层级,取出所有指定字段名的值
  9. /// </summary>
  10. public static List<string> FindAllValuesByKey(JsonData root, string targetKey)
  11. {
  12. var result = new List<string>();
  13. // 如果是对象
  14. if (root.IsObject)
  15. {
  16. // 遍历所有键
  17. foreach (string key in root.Keys)
  18. {
  19. // 找到目标字段 → 加入结果
  20. if (key == targetKey && root[key] != null)
  21. {
  22. result.Add(root[key].ToString());
  23. }
  24. // 递归遍历子节点
  25. if (root[key] != null)
  26. {
  27. result.AddRange(FindAllValuesByKey(root[key], targetKey));
  28. }
  29. }
  30. }
  31. // 如果是数组
  32. else if (root.IsArray)
  33. {
  34. foreach (JsonData item in root)
  35. {
  36. result.AddRange(FindAllValuesByKey(item, targetKey));
  37. }
  38. }
  39. return result;
  40. }
  41. }
  42. }