TopJsonReader.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Top.Api.Parser
  5. {
  6. /// <summary>
  7. /// TOP JSON响应通用读取器。
  8. /// </summary>
  9. public class TopJsonReader : ITopReader
  10. {
  11. private IDictionary json;
  12. public TopJsonReader(IDictionary json)
  13. {
  14. this.json = json;
  15. }
  16. public bool HasReturnField(object name)
  17. {
  18. return json.Contains(name);
  19. }
  20. public object GetPrimitiveObject(object name)
  21. {
  22. return json[name];
  23. }
  24. public object GetReferenceObject(object name, Type type, DTopConvert convert)
  25. {
  26. IDictionary dict = json[name] as IDictionary;
  27. if (dict != null && dict.Count > 0)
  28. {
  29. return convert(new TopJsonReader(dict), type);
  30. }
  31. else
  32. {
  33. return null;
  34. }
  35. }
  36. public IList GetListObjects(string listName, string itemName, Type type, DTopConvert convert)
  37. {
  38. IList listObjs = null;
  39. IDictionary jsonMap = json[listName] as IDictionary;
  40. if (jsonMap != null && jsonMap.Count > 0)
  41. {
  42. IList jsonList = jsonMap[itemName] as IList;
  43. if (jsonList != null && jsonList.Count > 0)
  44. {
  45. Type listType = typeof(List<>).MakeGenericType(new Type[] { type });
  46. listObjs = Activator.CreateInstance(listType) as IList;
  47. foreach (object item in jsonList)
  48. {
  49. if (typeof(IDictionary).IsAssignableFrom(item.GetType())) // object
  50. {
  51. IDictionary subMap = item as IDictionary;
  52. object subObj = convert(new TopJsonReader(subMap), type);
  53. if (subObj != null)
  54. {
  55. listObjs.Add(subObj);
  56. }
  57. }
  58. else if (typeof(IList).IsAssignableFrom(item.GetType())) // list or array
  59. {
  60. // TODO not support yet
  61. }
  62. else // string, bool, long, double, null, other
  63. {
  64. listObjs.Add(item);
  65. }
  66. }
  67. }
  68. }
  69. return listObjs;
  70. }
  71. }
  72. }