PageRenderTime 98ms CodeModel.GetById 38ms RepoModel.GetById 2ms app.codeStats 0ms

/wojilu/Serialization/JSON.cs

https://bitbucket.org/kingshine/wojilu
C# | 247 lines | 126 code | 57 blank | 64 comment | 25 complexity | 242174c02d63c273d1a09b4dd48f3686 MD5 | raw file
Possible License(s): MIT
  1. /*
  2. * Copyright 2010 www.wojilu.com
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using System.Reflection;
  20. using System.Text;
  21. using wojilu.ORM;
  22. using wojilu.Reflection;
  23. namespace wojilu.Serialization {
  24. /// <summary>
  25. /// 封装了 json 反序列化中的常见操作:将 json 字符串反序列化为对象、对象列表、字典等。
  26. /// 序列化工具见 JsonString
  27. /// </summary>
  28. public class JSON {
  29. /// <summary>
  30. /// 将字典序列化为 json 字符串
  31. /// </summary>
  32. /// <param name="dic"></param>
  33. /// <returns></returns>
  34. public static String DicToString( Dictionary<String, object> dic ) {
  35. return JsonString.ConvertDictionary( dic, false );
  36. }
  37. //----------------------------------------------------- String to obj ---------------------------------------------------------------------
  38. /// <summary>
  39. /// 将 json 字符串反序列化为对象
  40. /// </summary>
  41. /// <param name="oneJsonString">json 字符串</param>
  42. /// <param name="t">目标类型</param>
  43. /// <returns></returns>
  44. public static Object ToObject( String oneJsonString, Type t ) {
  45. Dictionary<String, object> map = JsonParser.Parse( oneJsonString ) as Dictionary<String, object>;
  46. return setValueToObject( t, map );
  47. }
  48. /// <summary>
  49. /// 将 json 字符串反序列化为对象
  50. /// </summary>
  51. /// <typeparam name="T"></typeparam>
  52. /// <param name="jsonString">json 字符串</param>
  53. /// <returns></returns>
  54. public static T ToObject<T>( String jsonString ) {
  55. Object result = ToObject( jsonString, typeof( T ) );
  56. return (T)result;
  57. }
  58. /// <summary>
  59. /// 将 json 字符串反序列化为对象列表
  60. /// </summary>
  61. /// <typeparam name="T"></typeparam>
  62. /// <param name="jsonString">json 字符串</param>
  63. /// <returns>返回对象列表</returns>
  64. public static List<T> ToList<T>( String jsonString ) {
  65. List<T> list = new List<T>();
  66. if (strUtil.IsNullOrEmpty( jsonString )) return list;
  67. List<object> lists = JsonParser.Parse( jsonString ) as List<object>;
  68. foreach (Dictionary<String, object> map in lists) {
  69. Object result = setValueToObject( typeof( T ), map );
  70. list.Add( (T)result );
  71. }
  72. return list;
  73. }
  74. internal static Object setValueToObject( Type t, Dictionary<String, object> map ) {
  75. Object result = rft.GetInstance( t );
  76. PropertyInfo[] properties = t.GetProperties( BindingFlags.Public | BindingFlags.Instance );
  77. foreach (KeyValuePair<String, object> pair in map) {
  78. String pName = pair.Key;
  79. String pValue = pair.Value.ToString();
  80. PropertyInfo info = getPropertyInfo( properties, pName );
  81. if ((info != null) && !info.IsDefined( typeof( NotSaveAttribute ), false )) {
  82. Object objValue;
  83. if (ReflectionUtil.IsBaseType( info.PropertyType )) {
  84. objValue = Convert.ChangeType( pValue, info.PropertyType );
  85. }
  86. else if (info.PropertyType == typeof( Dictionary<String, object> )) {
  87. objValue = pair.Value;
  88. }
  89. else if (rft.IsInterface( info.PropertyType, typeof( IList ) )) {
  90. objValue = pair.Value;
  91. }
  92. else {
  93. objValue = rft.GetInstance( info.PropertyType );
  94. ReflectionUtil.SetPropertyValue( objValue, "Id", cvt.ToInt( pValue ) );
  95. }
  96. ReflectionUtil.SetPropertyValue( result, pName, objValue );
  97. }
  98. }
  99. return result;
  100. }
  101. public static IEntity ToEntity( String jsonString, Type t ) {
  102. Dictionary<String, object> map = JsonParser.Parse( jsonString ) as Dictionary<String, object>;
  103. return toEntityByMap( t, map, null );
  104. }
  105. private static IEntity toEntityByMap( Type t, Dictionary<String, object> map, Type parentType ) {
  106. if (map == null) return null;
  107. IEntity result = Entity.New( t.FullName );
  108. EntityInfo ei = Entity.GetInfo( t );
  109. foreach (KeyValuePair<String, object> pair in map) {
  110. String pName = pair.Key;
  111. object pValue = pair.Value;
  112. EntityPropertyInfo p = ei.GetProperty( pName );
  113. Object objValue = null;
  114. if (ReflectionUtil.IsBaseType( p.Type )) {
  115. objValue = Convert.ChangeType( pValue, p.Type );
  116. }
  117. else if (p.IsList) {
  118. continue;
  119. }
  120. else if (pValue is Dictionary<String, object>) {
  121. if (p.Type == parentType) continue;
  122. Dictionary<String, object> dic = pValue as Dictionary<String, object>;
  123. if (dic != null && dic.Count > 0) {
  124. objValue = toEntityByMap( p.Type, dic, t );
  125. }
  126. }
  127. else
  128. continue;
  129. p.SetValue( result, objValue );
  130. }
  131. return result;
  132. }
  133. //--------------------------------------------------------------------------------------------------------------------------
  134. /// <summary>
  135. /// 将 json 字符串反序列化为字典对象的列表
  136. /// </summary>
  137. /// <param name="jsonString"></param>
  138. /// <returns></returns>
  139. public static List<Dictionary<String, object>> ToDictionaryList( String jsonString ) {
  140. List<object> list = JsonParser.Parse( jsonString ) as List<object>;
  141. List<Dictionary<String, object>> results = new List<Dictionary<String, object>>();
  142. foreach (Object obj in list) {
  143. Dictionary<String, object> item = obj as Dictionary<String, object>;
  144. results.Add( item );
  145. }
  146. return results;
  147. }
  148. /// <summary>
  149. /// 将 json 字符串反序列化为字典对象
  150. /// </summary>
  151. /// <param name="oneJsonString"></param>
  152. /// <returns></returns>
  153. public static Dictionary<String, object> ToDictionary( String oneJsonString ) {
  154. String str = trimBeginEnd( oneJsonString, "[", "]" );
  155. if (strUtil.IsNullOrEmpty( str )) return new Dictionary<String, object>();
  156. return JsonParser.Parse( str ) as Dictionary<String, object>;
  157. }
  158. private static String trimBeginEnd( String str, String beginStr, String endStr ) {
  159. str = str.Trim();
  160. str = strUtil.TrimStart( str, beginStr );
  161. str = strUtil.TrimEnd( str, endStr );
  162. str = str.Trim();
  163. return str;
  164. }
  165. private static PropertyInfo getPropertyInfo( PropertyInfo[] propertyList, String pName ) {
  166. foreach (PropertyInfo info in propertyList) {
  167. if (info.Name.Equals( pName )) {
  168. return info;
  169. }
  170. }
  171. return null;
  172. }
  173. /// <summary>
  174. /// 将引号、冒号、逗号进行编码
  175. /// </summary>
  176. /// <param name="str"></param>
  177. /// <returns></returns>
  178. public static String Encode( String str ) {
  179. return str.Replace( "\"", "&quot;" ).Replace( ":", "&#58;" ).Replace( ",", "&#44;" ).Replace( "'", "\\'" );
  180. }
  181. /// <summary>
  182. /// 将引号、冒号、逗号进行解码
  183. /// </summary>
  184. /// <param name="str"></param>
  185. /// <returns></returns>
  186. public static String Decode( String str ) {
  187. return str.Replace( "&quot;", "\"" ).Replace( "&#58;", ":" ).Replace( "&#44;", "," ).Replace( "\\'", "'" );
  188. }
  189. }
  190. }