private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			serializer.TypeNameHandling = TypeNameHandling.None;
			if (po.TryGetValue("type", out typeToken))
			{
				var type = typeToken.Value<string>().ToLowerInvariant();
				switch (type)
				{
					case "string":
						return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
					case "float":
					case "double":
					case "byte":
					case "short":
					case "integer":
					case "long":
						return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
					case "date":
						return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
					case "boolean":
						return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
					case "binary":
						return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				}
			}
			return null;
		}
Esempio n. 2
0
 public static EncryptedValuesReader FromObject(JObject encryptedValues)
 {
     var reader = encryptedValues.CreateReader();
     reader.Read();
     Debug.Assert(reader.TokenType == JsonToken.StartObject);
     reader.Read();
     return new EncryptedValuesReader(reader);
 }
Esempio n. 3
0
 JsonReader Rankings()
 {
     //  object with a property "Rank" where the value of every property is an array of ids in decending order by download
     //  e.g. {"Rank":["package-a","package-b","package-c"]}
     var ranking = new JObject
     {
         "Rank", new JArray(),
     };
     return ranking.CreateReader();
 }
        //This json converter is used to map the actual names that are given in the CopernicaField attributes.
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            //TODO: Cleanup!

            // Load JObject from stream and get the data object, it's where the actual information is.
            JObject jObject = JObject.Load(reader);
            var data = jObject["data"];

            //If data is empty the REST api returned nothing
            if(data.FirstOrDefault() == null)
                throw new CopernicaException("Data is empty");

            //This part is needed when retrieving the fields in order to validate the given object.
            if (objectType.Name == "CopernicaField")
            {
                //Create a list of CopernicaField to return
                return data.Select(item => new CopernicaField(item["name"].ToString())
                {
                    //All we need to know is the Name, Length and Type to validate.
                    Length = item["length"] == null ? 0 : (int)item["length"],
                    Type = (string) item["type"]
                }).ToList();
            }

            //Parse the data until only the object is left.
            dynamic a = JObject.Parse(data.First.ToString());
            dynamic b = JObject.Parse(a["fields"].ToString());
            var obj = (Object)Activator.CreateInstance(objectType);
            var jobject = new JObject(b);

            //Get all the properties and loop trough them. Then add all the properties with the correct names from je object.
            //This makes sure the mapping is right when deserializing the object.
            var properties = objectType.GetProperties().Where(x => x.GetCustomAttributes(false).Any(y => y.GetType() == typeof(CopernicaField) || y.GetType() == typeof(CopernicaKeyField)));
            var jobj = new JObject();
            foreach (var property in properties)
            {
                jobj.Add(property.Name, jobject[property.GetCustomAttribute<CopernicaField>().Name]);
            }

            //Populate the correct data in the object.
            JsonReader objreader = jobj.CreateReader();
            serializer.Populate(objreader, obj);

            return obj;
        }
Esempio n. 5
0
        public void Example()
        {
            #region Usage
            JObject o = new JObject
            {
                { "Cpu", "Intel" },
                { "Memory", 32 },
                {
                    "Drives", new JArray
                    {
                        "DVD",
                        "SSD"
                    }
                }
            };

            JsonReader reader = o.CreateReader();
            while (reader.Read())
            {
                Console.Write(reader.TokenType);
                if (reader.Value != null)
                {
                    Console.Write(" - " + reader.Value);
                }

                Console.WriteLine();
            }

            // StartObject
            // PropertyName - Cpu
            // String - Intel
            // PropertyName - Memory
            // Integer - 32
            // PropertyName - Drives
            // StartArray
            // String - DVD
            // String - SSD
            // EndArray
            // EndObject
            #endregion

            Assert.IsFalse(reader.Read());
        }
Esempio n. 6
0
 private IElasticType GetTypeFromJObject(JObject po, JsonSerializer serializer)
 {
     JToken typeToken;
     serializer.TypeNameHandling = TypeNameHandling.None;
     if (po.TryGetValue("type", out typeToken))
     {
         var type = typeToken.Value<string>().ToLowerInvariant();
         switch (type)
         {
             case "string":
                 return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
             case "float":
             case "double":
             case "byte":
             case "short":
             case "integer":
             case "long":
                 return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
             case "date":
                 return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
             case "boolean":
                 return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
             case "binary":
                 return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
             case "object":
                 return serializer.Deserialize(po.CreateReader(), typeof(ObjectMapping)) as ObjectMapping;
             case "nested":
                 return serializer.Deserialize(po.CreateReader(), typeof(NestedObjectMapping)) as NestedObjectMapping;
             case "multi_field":
                 return serializer.Deserialize(po.CreateReader(), typeof(MultiFieldMapping)) as MultiFieldMapping;
             case "ip":
                 return serializer.Deserialize(po.CreateReader(), typeof(IPMapping)) as IPMapping;
             case "geo_point":
                 return serializer.Deserialize(po.CreateReader(), typeof(GeoPointMapping)) as GeoPointMapping;
             case "geo_shape":
                 return serializer.Deserialize(po.CreateReader(), typeof(GeoShapeMapping)) as GeoShapeMapping;
             case "attachment":
                 return serializer.Deserialize(po.CreateReader(), typeof(AttachmentMapping)) as AttachmentMapping;
         }
     }
     return null;
 }
Esempio n. 7
0
			private static JsonReader CopyReaderForObject(JsonReader reader, JObject jObject)
			{
				var jObjectReader = jObject.CreateReader();
				jObjectReader.Culture = reader.Culture;
				jObjectReader.DateFormatString = reader.DateFormatString;
				jObjectReader.DateParseHandling = reader.DateParseHandling;
				jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
				jObjectReader.FloatParseHandling = reader.FloatParseHandling;
				jObjectReader.MaxDepth = reader.MaxDepth;
				jObjectReader.SupportMultipleContent = reader.SupportMultipleContent;
				return jObjectReader;
			}
        public void WriteEmptyToken()
        {
            JObject o = new JObject();
            JsonReader reader = o.CreateReader();
            while (reader.Read())
            {   
            }

            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();

            writer.WriteToken(reader);

            Assert.AreEqual(WriteState.Array, writer.WriteState);

            writer.WriteEndArray();

            StringAssert.AreEqual(@"[]", writer.Token.ToString());
        }
        public void WriteTokenWithParent()
        {
            JObject o = new JObject
            {
                ["prop1"] = new JArray(1),
                ["prop2"] = 1
            };

            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();

            writer.WriteToken(o.CreateReader());

            Assert.AreEqual(WriteState.Array, writer.WriteState);

            writer.WriteEndArray();

            Console.WriteLine(writer.Token.ToString());

            StringAssert.AreEqual(@"[
  {
    ""prop1"": [
      1
    ],
    ""prop2"": 1
  }
]", writer.Token.ToString());
        }
		private IDecayFunction ReadDecayFunction(string type, JObject o, JsonSerializer serializer)
		{
			var origin = o.Property("origin")?.Value.Type;
			if (origin == null) return null;
			var subType = "numeric";
			switch (origin)
			{
				case JTokenType.String:
					subType = "date";
					break;
				case JTokenType.Object:
					subType = "geo";
					break;
			}
			var t = DecayTypeMapping[$"{type}_{subType}"];
			return FromJson.Read(o.CreateReader(), t, null, serializer) as IDecayFunction;
		}
		private IElasticType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			JToken propertiesToken;
			JToken fieldsToken;
			var type = string.Empty;

			var hasType = po.TryGetValue("type", out typeToken);
			if (hasType)
				type = typeToken.Value<string>().ToLowerInvariant();
			else if (po.TryGetValue("properties", out propertiesToken))
				type = "object";

			var originalType = type;
			var hasFields = po.TryGetValue("fields", out fieldsToken);
			if (hasFields)
				type = "multi_field";

			serializer.TypeNameHandling = TypeNameHandling.None;

			switch (type)
			{
				case "string":
					return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
				case "float":
				case "double":
				case "byte":
				case "short":
				case "integer":
				case "long":
					return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
				case "date":
					return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
				case "boolean":
					return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
				case "binary":
					return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				case "object":
					return serializer.Deserialize(po.CreateReader(), typeof(ObjectMapping)) as ObjectMapping;
				case "nested":
					return serializer.Deserialize(po.CreateReader(), typeof(NestedObjectMapping)) as NestedObjectMapping;
				case "multi_field":
					var m =serializer.Deserialize(po.CreateReader(), typeof(MultiFieldMapping)) as MultiFieldMapping;
					m.Type = originalType;
					return m;
				case "ip":
					return serializer.Deserialize(po.CreateReader(), typeof(IPMapping)) as IPMapping;
				case "geo_point":
					return serializer.Deserialize(po.CreateReader(), typeof(GeoPointMapping)) as GeoPointMapping;
				case "geo_shape":
					return serializer.Deserialize(po.CreateReader(), typeof(GeoShapeMapping)) as GeoShapeMapping;
				case "attachment":
					return serializer.Deserialize(po.CreateReader(), typeof(AttachmentMapping)) as AttachmentMapping;
			}

			return null;
		}
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var currentResourceInstance = (IResource)Activator.CreateInstance(objectType);
            var jToken = JToken.ReadFrom(reader);
            if (jToken[ReservedPropertyNames.Relations] != null)
            {
                currentResourceInstance.Relations = serializer.Deserialize<Relations>(jToken[ReservedPropertyNames.Relations].CreateReader());
            }

            var simpleProperties =
                jToken.Where(_ => _.GetType() == typeof (JProperty))
                    .Cast<JProperty>()
                    .Where(_ => !ReservedPropertyNames.Names.Contains(_.Name));

            // Create a new JObject that will receive all "simple" non-reserved properties.
            // This will be the vehicle to populate the resource instance.
            var populater = new JObject();
            foreach (JProperty jProperty in simpleProperties)
            {
                populater.Add(jProperty);
            }

            serializer.Populate(populater.CreateReader(), currentResourceInstance);

            if (jToken[ReservedPropertyNames.EmbeddedResources] != null)
            {
                JToken embeddedResourceObject = jToken[ReservedPropertyNames.EmbeddedResources];
                foreach (var embeddedObjectProperty in embeddedResourceObject.Where(_ => _.GetType() == typeof(JProperty)).Cast<JProperty>())
                {
                    if (embeddedObjectProperty.Value.GetType() == typeof (JArray))
                    {
                        if (objectType.Name.ToLower().Contains(embeddedObjectProperty.Name))
                        {
                            var dynamicCurrent = (dynamic)currentResourceInstance;
                            var itemsProperty = objectType.GetProperty("Items");
                            var collectionResourceType = itemsProperty.PropertyType.GetGenericArguments().First();

                            // Recursion
                            foreach (var arrayElem in ((JArray) embeddedObjectProperty.Value))
                            {
                                var resourceElem =
                                    (IResource)
                                        serializer.Deserialize(arrayElem.CreateReader(), collectionResourceType);
                            
                                dynamicCurrent.AddItem(resourceElem);
                            }
                        }
                    }
                    else
                    {
                        var assignableProperty = objectType.GetProperties()
                            .Where(_ => typeof (IResource).IsAssignableFrom(_.PropertyType))
                            .FirstOrDefault(_ => _.PropertyType.Name.ToLower().Contains(embeddedObjectProperty.Name));
                        if (assignableProperty != null)
                        {
                            // Recursion
                            var resourceElem = serializer.Deserialize(embeddedObjectProperty.Value.CreateReader(),
                                assignableProperty.PropertyType);
                            assignableProperty.SetValue(currentResourceInstance, resourceElem);
                        }
                    }
                }
            }

            return currentResourceInstance;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var depth = reader.Depth;

            string[] columns = null;

            var contract = (JsonArrayContract)serializer.ContractResolver.ResolveContract(objectType);

            object ret = existingValue;

            while (reader.Read() && reader.TokenType != JsonToken.EndObject && reader.Depth > depth)
            {
               while (reader.TokenType == JsonToken.PropertyName)
               {
                   var prop = (string)reader.Value;
                   if (prop == "columns")
                   {
                       reader.Read();
                       columns = serializer.Deserialize<string[]>(reader);
                   }
                   else if (prop == "data")
                   {
                       if (columns == null || columns.Length == 0)
                       {
                           reader.Skip();
                       }
                       else
                       {
                           //Deserialize the data part

                           if (existingValue == null)
                           {
                               if (contract.DefaultCreator != null)
                               {
                                   ret = contract.DefaultCreator();
                               }
                               else
                               {
                                   ret = Activator.CreateInstance(objectType);
                               }
                           }

                           var collectionItemType = contract.CollectionItemType;

                           var lst = (IList) ret;
                           if (!(reader.Read() && reader.TokenType == JsonToken.StartArray))
                           {
                               throw new Exception("Expected to read an array");
                           }

                           int arrayDepth = reader.Depth;
                           while (reader.Read() && (reader.TokenType != JsonToken.EndArray && reader.Depth >= arrayDepth))
                           {
                               //This is a row
                               var item = new JObject();

                               if (reader.TokenType != JsonToken.StartArray)
                                   throw new Exception("Expected to read an array but found " + reader.TokenType.ToString());

                               int index = 0;
                               int arrayDepth2 = reader.Depth;
                               while (reader.Read() &&
                                      (reader.TokenType != JsonToken.EndArray && reader.Depth >= arrayDepth2))
                               {
                                   item[columns[index]] = JToken.ReadFrom(reader);
                                   index++;
                               }

                               using (var subReader = item.CreateReader())
                               {
                                   lst.Add(serializer.Deserialize(subReader, collectionItemType));
                               }
                           }

                           if (reader.Depth > arrayDepth)
                               throw new JsonReaderException("Unexpected end of content while reading array.");
                       }
                   }
                   else
                   {
                       reader.Skip();
                   }
               }
            }

            return ret;
        }
        private static void InitObject(JsonSerializer serializer, object target, string href, JObject item)
        {
            var crestObject = (ICrestObject) target;
            crestObject.Href = href;

            serializer.Populate(item.CreateReader(), target);
            Task.Run(() => Crest.Settings.Cache.Put(crestObject));
        }