Ejemplo n.º 1
0
		private object PopulateObject(JsonReader reader, Type objectType)
		{
			object newObject = Activator.CreateInstance(objectType);

			while (reader.Read())
			{
				switch (reader.TokenType)
				{
					case JsonToken.PropertyName:
						string memberName = reader.Value.ToString();

						SetObjectMember(reader, newObject, objectType, memberName);
						break;
					case JsonToken.EndObject:
						return newObject;
					default:
						throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
				}
			}

			throw new JsonSerializationException("Unexpected end when deserializing object.");
		}
Ejemplo n.º 2
0
		private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName)
		{
			if (!reader.Read())
				throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));

			MemberMappingCollection memberMappings = GetMemberMappings(targetType);
			Type memberType;
			object value;

			// test if a member with memberName exists on the type
			// otherwise test if target is a dictionary and assign value with the key if it is
			if (memberMappings.Contains(memberName))
			{
				MemberMapping memberMapping = memberMappings[memberName];

				if (memberMapping.Ignored)
					return;

				// ignore member if it is readonly
				if (!memberMapping.Writable)
					return;

				// get the member's underlying type
				memberType = ReflectionUtils.GetMemberUnderlyingType(memberMapping.Member);

				value = GetObject(reader, memberType);

				ReflectionUtils.SetMemberValue(memberMapping.Member, target, value);
			}
			else if (typeof(IDictionary).IsAssignableFrom(targetType))
			{
				// attempt to get the IDictionary's type
				memberType = ReflectionUtils.GetDictionaryValueType(target.GetType());

				value = GetObject(reader, memberType);

				((IDictionary)target).Add(memberName, value);
			}
			else
			{
                if( memberName != "__type" )
				    throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
			}
		}
Ejemplo n.º 3
0
		private object PopulateList(JsonReader reader, Type objectType)
		{
			Type elementType = ReflectionUtils.GetListItemType(objectType);

			IList populatedList = CollectionUtils.CreateList(objectType);
			while (reader.Read())
			{
				switch (reader.TokenType)
				{
					case JsonToken.EndArray:
						return populatedList;
					case JsonToken.Comment:
						break;
					default:
						object value = GetObject(reader, elementType);
						populatedList.Add(value);
						break;
				}
			}
			throw new JsonSerializationException("Unexpected end when deserializing array.");
		}
Ejemplo n.º 4
0
		private JavaScriptObject PopulateJavaScriptObject(JsonReader reader)
		{
			JavaScriptObject jsObject = new JavaScriptObject();

			while (reader.Read())
			{
				switch (reader.TokenType)
				{
					case JsonToken.PropertyName:
						string memberName = reader.Value.ToString();

						// move to the value token. skip comments
						do
						{
							if (!reader.Read())
								throw new JsonSerializationException("Unexpected end while deserializing object.");
						} while (reader.TokenType == JsonToken.Comment);

						object value = GetObject(reader, null);

						jsObject[memberName] = value;
						break;
					case JsonToken.EndObject:
						return jsObject;
					case JsonToken.Comment:
						break;
					default:
						throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType);
				}
			}

			throw new JsonSerializationException("Unexpected end while deserializing object.");
		}
Ejemplo n.º 5
0
		private object GetObject(JsonReader reader, Type objectType)
		{
			_level++;

			object value;
			JsonConverter converter;

			if (HasMatchingConverter(objectType, out converter))
			{
				return converter.ReadJson(reader, objectType);
			}
			else
			{
				switch (reader.TokenType)
				{
						// populate a typed object or generic dictionary/array
						// depending upon whether an objectType was supplied
					case JsonToken.StartObject:
						value = (objectType != null) ? PopulateObject(reader, objectType) : PopulateJavaScriptObject(reader);
						break;
					case JsonToken.StartArray:
						value = (objectType != null) ? PopulateList(reader, objectType) : PopulateJavaScriptArray(reader);
						break;
					case JsonToken.Integer:
					case JsonToken.Float:
					case JsonToken.String:
					case JsonToken.Boolean:
					case JsonToken.Date:
						value = EnsureType(reader.Value, objectType);
						break;
					case JsonToken.Constructor:
						value = reader.Value.ToString();
						break;
					case JsonToken.Null:
					case JsonToken.Undefined:
						value = null;
						break;
					default:
						throw new JsonSerializationException("Unexpected token whil deserializing object: " + reader.TokenType);
				}
			}

			_level--;

			return value;
		}
Ejemplo n.º 6
0
		private JavaScriptArray PopulateJavaScriptArray(JsonReader reader)
		{
			JavaScriptArray jsArray = new JavaScriptArray();

			while (reader.Read())
			{
				switch (reader.TokenType)
				{
					case JsonToken.EndArray:
						return jsArray;
					case JsonToken.Comment:
						break;
					default:
						object value = GetObject(reader, null);

						jsArray.Add(value);
						break;
				}
			}

			throw new JsonSerializationException("Unexpected end while deserializing array.");
		}
Ejemplo n.º 7
0
		/// <summary>
		/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
		/// into an instance of the specified type.
		/// </summary>
		/// <param name="reader">The type of object to create.</param>
		/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
		/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
		public object Deserialize(JsonReader reader, Type objectType)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			if (!reader.Read())
				return null;

			return GetObject(reader, objectType);
		}
Ejemplo n.º 8
0
		/// <summary>
		/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="JsonReader"/> that contains the Json structure to deserialize.</param>
		/// <returns>The <see cref="Object"/> being deserialized.</returns>
		public object Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}
Ejemplo n.º 9
0
		public virtual object ReadJson(JsonReader reader, Type objectType)
		{
			throw new NotImplementedException(string.Format("{0} has not overriden FromJson method.", GetType().Name));
		}
Ejemplo n.º 10
0
 /// <summary>
 /// 获取参数
 /// </summary>
 bool GetParams()
 {
     //if (isProxy)
     //{
     //    byte[] data = new byte[1024];
     //    //IPAddress ip = IPAddress.Parse(proxy);
     //    //IPEndPoint ipEnd = new IPEndPoint(ip, proxyPort);
     //    ///重连X次
     //    for (int i = 0; i < 1; i++)
     //    {
     //        try
     //        {
     //            //socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     //            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
     //            //Common.NowMsg = "代理" + proxy + ":" + proxyPort + "【获取参数】连接中,";
     //            //socket.Connect(ipEnd);
     //            StringBuilder buf = new StringBuilder();
     //            buf.Append("GET ").Append("http://yy.com//get-data/9999?subSid=125233252&type=main&_=137493045" + new Random().Next(1, 9) + "9" + new Random().Next(1, 9)).Append(" HTTP/1.1\r\n");
     //            buf.Append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\r\n");
     //            buf.Append("Host: yy.com\r\n");
     //            buf.Append("Proxy-Connection: Keep-Alive\r\n");
     //            buf.Append("\r\n");
     //            byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString());
     //            //发送
     //            socket.Send(ms);
     //            string jsonStr = string.Empty;
     //            int recv = 0;
     //            do
     //            {
     //                recv = socket.Receive(data);
     //                if (recv > 0)
     //                    jsonStr += (Encoding.Default.GetString(data, 0, recv));
     //                //判断参数结尾
     //                if (jsonStr.IndexOf("core.bmp\"}") != -1)
     //                    break;
     //            } while (recv != 0);
     //            socket.Close();
     //            if (jsonStr.IndexOf("200 OK") == -1)//未取到参数
     //            {
     //                Common.ProxyManager.Score(proxy, ScoreType.Discard);
     //                if (Common.LogSwitch)
     //                    lastMsg = "代理服务器未返回有效参数";
     //                continue;
     //            }
     //            jsonStr = jsonStr.Substring(jsonStr.IndexOf("{\""));
     //            StringReader sread = new StringReader(jsonStr);
     //            JsonReader jr = new JsonReader(sread);
     //            JsonSerializer js = new JsonSerializer();
     //            NetParams np = (NetParams)js.Deserialize(jr, typeof(NetParams));
     //            netParams = np;
     //            server = netParams.pps[0].ip;
     //            port = netParams.pps[0].ports[0];
     //            lastMsg = "获取参数完成";
     //            break;
     //        }
     //        catch (SocketException se)
     //        {
     //            if (se.ErrorCode == 10060)
     //                if (Common.LogSwitch)
     //                    lastMsg = "代理服务器无回应";
     //                else if (se.ErrorCode == 10061)
     //                    if (Common.LogSwitch)
     //                        lastMsg = "代理服务器拒绝连接";
     //                    else
     //                        lastMsg = "";
     //        }
     //        catch (Exception e)
     //        {
     //            //异常
     //            Common.ProxyManager.Score(proxy, ScoreType.Exception);
     //            if (Common.LogSwitch)
     //                lastMsg = "参数数据异常。";
     //            return false;
     //        }
     //    }
     //}
     //else
     {
         try
         {
             lastMsg = "获取参数...";
             HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(tagUrl, null, null, null);
             StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
             string jsonStr = sr.ReadToEnd();
             StringReader sread = new StringReader(jsonStr);
             JsonReader jr = new JsonReader(sread);
             JsonSerializer js = new JsonSerializer();
             NetParams np = (NetParams)js.Deserialize(jr, typeof(NetParams));
             netParams = np;
             //设置缺省服务器及端口
             server = netParams.pps[0].ip;
             port = netParams.pps[0].ports[0];
             lastMsg = "获取参数完成";
         }
         catch (Exception e)
         {
             if (Common.LogSwitch)
                 lastMsg = "获取参数失败,可能是网速太差。";
             return false;
         }
     }
     return true;
 }