예제 #1
0
		/// <summary>
		/// Reads the JSON representation of the object.
		/// </summary>
		/// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param>
		/// <param name="objectType">Type of the object.</param>
		/// <param name="existingValue">The existing value of object being read.</param>
		/// <param name="serializer">The calling serializer.</param>
		/// <returns>The object value.</returns>
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var enumType = Nullable.GetUnderlyingType(objectType) ?? objectType;
			if (enumType != objectType && reader.TokenType == JsonToken.Null)//nullable
				return null;
			return Enum.Parse(enumType, reader.Value.ToString(), true);
		}
예제 #2
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            reader.Read();

            Debug.Assert(reader.TokenType == JsonToken.PropertyName);
            Debug.Assert((string)reader.Value == "coordinates");

            if (objectType == typeof(Coordinate))
            {
                return ReadJsonCoordinate(reader);
            }

            if (typeof(IEnumerable<Coordinate>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinates(reader);
            }

            if (typeof(List<Coordinate[]>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable(reader);
            }
            if (typeof(List<List<Coordinate[]>>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable2(reader);
            }

            throw new Exception();
        }
 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <remarks>
 /// this converter will never be needed to deserialize from json -
 ///  built-in converter is enough as Json.Net serializes any collection - including IEnumerable{T} to json arrays.
 /// </remarks>
 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing value of object being read.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>executing this method will throw <see cref="NotSupportedException">NotSupportedException</see> since this converter should not be used for reading</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     //this converter will never be needed to deserialize from json - built-in converter is enough as
     //Json.Net serializes any collection - including IEnumerable<T> to json arrays.
     throw new NotSupportedException(@"JsonLinqEnumerableConverter should not be used to deserialize collections from json - 
                                     if this exception gets thrown, it is probably a bug.");
 }
예제 #4
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.Null)
				return null;

			return wktReader.Read((string)reader.Value);
		}
		/// <summary>
		/// Reads the JSON representation of the object.
		/// </summary>
		/// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param>
		/// <param name="objectType">Type of the object.</param>
		/// <param name="existingValue">The existing value of object being read.</param>
		/// <param name="serializer">The calling serializer.</param>
		/// <returns>The object value.</returns>
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			// Handle null values
			if (reader.TokenType == JsonToken.Null) return null;

			var arrayItemType = objectType.GetElementType();
			var arrayRank = objectType.GetArrayRank();

			// Retrieve all the values from the Json
			var arrayValues = ReadRank(reader, serializer, arrayItemType);

			// Determine the lengths of all ranks for the array
			var rankLengthList = GetRankLengthList(arrayValues);

			// If empty values were found, make sure the ranks match in size
			for (var i = rankLengthList.Count; i < arrayRank; i++)
			{
				rankLengthList.Add(0);
			}

			var rankLengthArray = rankLengthList.ToArray();

			// Create the array that will hold the values
			var retVal = Array.CreateInstance(arrayItemType, rankLengthArray);

			// Make the assignments
			SetValues(retVal, rankLengthArray, new int[0], 0, arrayValues);

			return retVal;
		}
예제 #6
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     JToken jo = JToken.Load(reader);
     System.Net.IPAddress address = jo["Address"].ToObject<System.Net.IPAddress>(serializer);
     int port = jo["Port"].Value<int>();
     return new System.Net.IPEndPoint(address, port);
 }
예제 #7
0
		/// <summary>
		/// Reads the JSON representation of the object.
		/// </summary>
		/// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param>
		/// <param name="objectType">Type of the object.</param>
		/// <param name="existingValue">The existing value of object being read.</param>
		/// <param name="serializer">The calling serializer.</param>
		/// <returns>The object value.</returns>
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
		    var token = RavenJToken.ReadFrom(reader);
		    var val = token as RavenJValue;
		    if(val != null)
		        return val.Value;
		    var array = token as RavenJArray;
			if (array != null)
			{
				var dynamicJsonObject = new DynamicJsonObject(new RavenJObject());
				return new DynamicList(array.Select(dynamicJsonObject.TransformToValue).ToArray());
			}

			var typeName = token.Value<string>("$type");
			if(typeName != null)
			{
				var type = Type.GetType(typeName, false);
				if(type != null)
				{
					return serializer.Deserialize(new RavenJTokenReader(token), type);
				}
			}

		    return new DynamicJsonObject((RavenJObject)((RavenJObject)token).CloneToken());
		}
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var collection = new NameValueCollection();

			while (reader.Read())
			{
				if (reader.TokenType == JsonToken.EndObject)
					break;

				var key = (string)reader.Value;

				if (reader.Read() == false)
					throw new InvalidOperationException("Expected PropertyName, got " + reader.TokenType);

				if (reader.TokenType == JsonToken.StartArray)
				{
					var values = serializer.Deserialize<string[]>(reader);
					foreach (var value in values)
					{
						collection.Add(key, value);
					}
				}
				else
				{
					collection.Add(key, reader.Value.ToString());
				}
			}

			return collection;
		}
예제 #9
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            var keyType = objectType.GetGenericArguments()[0];
            var keyValueType = keyType.BaseType.GetGenericArguments()[0];
            var valueType = objectType.GetGenericArguments()[1];
            var intermediateDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), valueType);
            var intermediateDictionary = (IDictionary)Activator.CreateInstance(intermediateDictionaryType);
            serializer.Populate(reader, intermediateDictionary);

            var valueProperty = keyType.GetProperty("Value");
            var finalDictionary = (IDictionary)Activator.CreateInstance(objectType);
            foreach (DictionaryEntry pair in intermediateDictionary)
            {
                object value;
                if (keyValueType == typeof(Guid))
                    value = Guid.Parse(pair.Key.ToString());
                else
                    value = Convert.ChangeType(pair.Key, keyValueType, null);

                var key = Activator.CreateInstance(keyType);
                valueProperty.SetValue(key, value, null);
                finalDictionary.Add(key, pair.Value);
            }
            return finalDictionary;
        }
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var s = reader.Value as string;
		    if(s != null)
			{
				if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
				{
					DateTime time;
					if (DateTime.TryParseExact(s, Default.DateTimeFormatsToRead, CultureInfo.InvariantCulture,
					                           DateTimeStyles.RoundtripKind, out time))
					{
						if (time.Kind == DateTimeKind.Unspecified)
							return DateTime.SpecifyKind(time, DateTimeKind.Local);
						if (s.EndsWith("+00:00"))
							return time.ToUniversalTime();
						return time;
					}
				}
				if(objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
				{
					DateTimeOffset time;
					if (DateTimeOffset.TryParseExact(s, Default.DateTimeFormatsToRead, CultureInfo.InvariantCulture,
											   DateTimeStyles.RoundtripKind, out time))
						return time;
				}

			}
			return DeferReadToNextConverter(reader, objectType, serializer, existingValue);
		}
예제 #11
0
 protected object Deserialize(JsonReader reader, Type type)
 {
     using (RavenJTokenReader tokenReader = new RavenJTokenReader(RavenJToken.ReadFrom(reader)))
     {
         return serializer.Deserialize(tokenReader, type);
     }
 }
예제 #12
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var s = reader.Value as string;
     if (s == null)
         return null;
     return Etag.Parse(s);
 }
예제 #13
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                var jsonObject = JObject.Load(reader);
                var className = jsonObject.Property("ClassName").Value.ToString();
                var name = jsonObject.Property("Name").Value.ToString();
                var assemblyName = jsonObject.Property("AssemblyName").Value.ToString();
                var signature = jsonObject.Property("Signature").Value.ToString();

                var start = signature.IndexOf('(') + 1;
                var end = signature.IndexOf(')');
                var parametersString = signature.Substring(start, end - start);
                var parameterTypeStrings = parametersString.Split(',');

                if (string.IsNullOrEmpty(className) ||
                    string.IsNullOrEmpty(name) ||
                    string.IsNullOrEmpty(assemblyName) ||
                    parameterTypeStrings == null)
                    throw new ArgumentException("Json object is not representing a MethodInfo");

                var typeName = string.Format("{0}, {1}", className, assemblyName);
                var type = Type.GetType(typeName);
                var method = type.GetMethods().Where(m => m.Name.Equals(name) && DoesSignatureMatch(m, parameterTypeStrings)).SingleOrDefault();
                return method;
            }
            catch {
                return null;
            }
        }
예제 #14
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			// NOTE: THIS DOESN'T SUPPORT READING OF DynamicJsonObject !!!

			var o = RavenJToken.Load(reader);
			return (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined) ? null : o;
		}
예제 #15
0
		protected object DeferReadToNextConverter(JsonReader reader, Type objectType, JsonSerializer serializer, object existingValue)
		{
			var anotherConverter = serializer.Converters
				.Skip(serializer.Converters.IndexOf(this) + 1)
				.FirstOrDefault(x => x.CanConvert(objectType));
			if (anotherConverter != null)
				return anotherConverter.ReadJson(reader, objectType, existingValue, serializer);
			return reader.Value;
		}
예제 #16
0
			public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
			{
				var readAsString = reader.Value.ToString();
				var strings = readAsString.Split(':');
				return new Money
				{
					Currency = strings[0],
					Amount = decimal.Parse(strings[1])
				};
			}
		public object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.Null)
				return null;

			var json = RavenJToken.ReadFrom(reader);
			object result;
			TryRead(json as RavenJObject, out result); // Throw exception?
			return result;
		}
예제 #18
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var instance = Activator.CreateInstance(objectType);
            var genericArgumentType = objectType.BaseType.GetGenericArguments()[0];
            var value = reader.Value;
            if (genericArgumentType == typeof(Guid))
                value = Guid.Parse(reader.Value.ToString());

            objectType.GetProperty("Value").SetValue(instance, value, null);
            return instance;
        }
예제 #19
0
 /// <summary>
 ///     Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">
 ///     The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.
 /// </param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing value of object being read.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>
 ///     The object value.
 /// </returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                 JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
         return null;
     object obj = Container.Resolve(objectType);
     if (obj == null)
         throw new JsonSerializationException("No object created.");
     serializer.Populate(reader, obj);
     return obj;
 }
 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing value of object being read.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var input = reader.Value as string;
     if (input != null && luceneDateTimePattern.IsMatch(input))
     {
         var stringToDate = DateTools.StringToDate(input);
         if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
             return new DateTimeOffset(stringToDate, DateTimeOffset.Now.Offset);
         return DateTime.SpecifyKind(stringToDate, DateTimeKind.Local);
     }
     return reader.Value;
 }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param><param name="objectType">Type of the object.</param><param name="existingValue">The existing value of object being read.</param><param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
                return DeferReadToNextConverter(reader, objectType, serializer, existingValue);

            var jObject = RavenJObject.Load(reader);
            var dateTime = jObject.Value<DateTime>("DateTime");
            return new DateTimeOffset(
                dateTime.Year,dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond,
                TimeSpan.FromMilliseconds(jObject.Value<double>("Offset"))
                );
        }
예제 #22
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			string value = reader.Value as string;
			if (value != null)
			{
				float result;
				if (float.TryParse(value, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
				                   CultureInfo.InvariantCulture, out result))
					return result;
			}
			if (reader.Value == null)
				return null;
			return Convert.ChangeType(reader.Value, typeof(float), CultureInfo.InvariantCulture);
	  
		}
예제 #23
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var address = JToken.Load(reader).ToString();
            System.Net.IPAddress ipaddress = null;
            try
            {
                ipaddress = System.Net.IPAddress.Parse(address);

            }
            catch (Exception)
            {

                throw;
            }

            return ipaddress;
        }
예제 #24
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartObject)
            {
                var denormalizedReference = new DenormalizedReference();
                serializer.Populate(reader, denormalizedReference);

                var referenceInstace = _generator.CreateClassProxyWithTarget(
                    denormalizedReference.ReferenceInstanceType,
                    new Type[] { typeof(IDynamicProxy) },
                    InstanceCreator.Create(denormalizedReference.ReferenceInstanceType),
                    new ReferenceInterceptor(denormalizedReference.Id, denormalizedReference.ReferenceInstanceType));

                return referenceInstace;
            }
            return null;
        }
예제 #25
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            reader.Read();
            if (!(reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "geometries"))
            {
                throw new Exception();
            }
            reader.Read();
            if (reader.TokenType != JsonToken.StartArray)
                throw new Exception();

            reader.Read();
            List<IGeometry> geoms = new List<IGeometry>();
            while (reader.TokenType != JsonToken.EndArray)
            {
                JObject obj = (JObject)serializer.Deserialize(reader);
                GeoJsonObjectType geometryType = (GeoJsonObjectType)Enum.Parse(typeof(GeoJsonObjectType), obj.Value<string>("type"));

                switch (geometryType)
                {
                    case GeoJsonObjectType.Point:
                        geoms.Add(this._factory.CreatePoint(ToCoordinate(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.LineString:
                        geoms.Add(this._factory.CreateLineString(ToCoordinates(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.Polygon:
                        geoms.Add(this.CreatePolygon(ToListOfCoordinates(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.MultiPoint:
                        geoms.Add(this._factory.CreateMultiPoint(ToCoordinates(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.MultiLineString:
                        geoms.Add(this.CreateMultiLineString(ToListOfCoordinates(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.MultiPolygon:
                        geoms.Add(this.CreateMultiPolygon(ToListOfListOfCoordinates(obj.Value<JArray>("coordinates"))));
                        break;
                    case GeoJsonObjectType.GeometryCollection:
                        throw new NotSupportedException();

                }
                reader.Read();
            }
            return geoms;
        }
예제 #26
0
 /// <summary>
 ///     Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">
 ///     The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.
 /// </param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing value of object being read.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>
 ///     The object value.
 /// </returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                 JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
         return null;
     using (var scope=Container.BeginScope())
     {
         object obj = scope.Resolve(objectType);
         if (obj == null)
             throw new JsonSerializationException("No object created.");
         serializer.Populate(reader, obj);
         /*RefrenceHacks.SkipRefrences = true;
         scope.Scope.InjectUnsetProperties(obj);
         RefrenceHacks.SkipRefrences = false;*/
         return obj;
     }
 }
예제 #27
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Debug.Assert(reader.TokenType == JsonToken.PropertyName);
            Debug.Assert((string)reader.Value == "bbox");

            JArray envelope = serializer.Deserialize<JArray>(reader);
            Debug.Assert(envelope.Count == 4);

            double minX = Double.Parse((string)envelope[0]);
            double minY = Double.Parse((string)envelope[1]);
            double maxX = Double.Parse((string)envelope[2]);
            double maxY = Double.Parse((string)envelope[3]);

            Debug.Assert(minX <= maxX);
            Debug.Assert(minY <= maxY);

            return new Envelope(minX, minY, maxX, maxY);
        }
        private Model ReadModel(JsonReader reader) {
            while (reader.TokenType == JsonToken.Comment) {
                if (!reader.Read()) throw new JsonSerializationException("Unexpected Token when converting Model object");
            }

            if (reader.TokenType != JsonToken.StartObject) {
                throw new JsonSerializationException("Unexpected Token when converting Model object");
            }

            var obj = new Model { };

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

                        if (!reader.Read()) {
                            throw new JsonSerializationException("Unexpected end when reading Model object");
                        }

                        if (propertyName == "Id") {
                            obj.Id = (string)this.ReadValue(reader);
                            break;
                        }

                        if (propertyName == "_shurikenMeta") {
                            obj._shurikenMeta = this.ReadMetaData(reader);
                            break;
                        }

                        var v = this.ReadValue(reader);

                        obj[propertyName] = v;
                        break;
                    case JsonToken.Comment:
                        break;
                    case JsonToken.EndObject:
                        return obj;
                }
            }

            throw new JsonSerializationException("Unexpected end when reading Model object");
        }
		/// <summary>
		/// Read in all the values from the Json reader and populate a nested ArrayList
		/// </summary>
		/// <param name="reader">JsonReader to use</param>
		/// <param name="serializer">JsonSerializer to use</param>
		/// <returns></returns>
		private List<object> ReadRank(JsonReader reader, JsonSerializer serializer)
		{
			var retVal = new List<object>();

			reader.Read();

			while (reader.TokenType != JsonToken.EndArray && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.EndObject)
			{
				// If another array is found, it is a new rank
				// Otherwise, we have a value
				if (reader.TokenType == JsonToken.StartArray)
					retVal.Add(ReadRank(reader, serializer));
				else
					retVal.Add(reader.Value);

				reader.Read();
			}

			return retVal;
		}
예제 #30
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var arr = serializer.Deserialize<double[]>(reader);

            if (arr != null)
            {
                if (arr.Length == 2)
                    return new Coordinate(arr[1], arr[0]);

                if (arr.Length == 3)
                    return new CoordinateZ(arr[1], arr[0], arr[2]);

                if (arr.Length == 4 && double.IsNaN(arr[2]))
                    return new CoordinateM(arr[1], arr[0], arr[3]);

                if (arr.Length == 4)
                    return new CoordinateZM(arr[1], arr[0], arr[2], arr[3]);
            }

            return null;
        }