当前位置: 首页>>代码示例>>C#>>正文


C# JObject.CreateReader方法代码示例

本文整理汇总了C#中Newtonsoft.Json.Linq.JObject.CreateReader方法的典型用法代码示例。如果您正苦于以下问题:C# JObject.CreateReader方法的具体用法?C# JObject.CreateReader怎么用?C# JObject.CreateReader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Newtonsoft.Json.Linq.JObject的用法示例。


在下文中一共展示了JObject.CreateReader方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetTypeFromJObject

		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;
		}
开发者ID:BiYiTuan,项目名称:elasticsearch-net,代码行数:28,代码来源:ElasticCoreTypeConverter.cs

示例2: FromObject

 public static EncryptedValuesReader FromObject(JObject encryptedValues)
 {
     var reader = encryptedValues.CreateReader();
     reader.Read();
     Debug.Assert(reader.TokenType == JsonToken.StartObject);
     reader.Read();
     return new EncryptedValuesReader(reader);
 }
开发者ID:darilek,项目名称:dotvvm,代码行数:8,代码来源:EncryptedValuesReader.cs

示例3: Rankings

 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();
 }
开发者ID:NuGet,项目名称:Entropy,代码行数:10,代码来源:AuxillaryIndexLoader.cs

示例4: ReadJson

        //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;
        }
开发者ID:DdeMoel,项目名称:CopernicaNET,代码行数:46,代码来源:JsonFieldsConverter.cs

示例5: Example

        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());
        }
开发者ID:ChuangYang,项目名称:Newtonsoft.Json,代码行数:43,代码来源:CreateReader.cs

示例6: GetTypeFromJObject

 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;
 }
开发者ID:romankor,项目名称:NEST,代码行数:42,代码来源:ElasticTypeConverter.cs

示例7: CopyReaderForObject

			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;
			}
开发者ID:cssack,项目名称:CsGlobals,代码行数:12,代码来源:CssPacket.cs

示例8: WriteEmptyToken

        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());
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:20,代码来源:JTokenWriterTest.cs

示例9: WriteTokenWithParent

        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());
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:29,代码来源:JTokenWriterTest.cs

示例10: ReadDecayFunction

		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;
		}
开发者ID:RossLieberman,项目名称:NEST,代码行数:17,代码来源:ScoreFunctionJsonConverter.cs

示例11: GetTypeFromJObject

		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;
		}
开发者ID:BiYiTuan,项目名称:elasticsearch-net,代码行数:57,代码来源:ElasticTypeConverter.cs

示例12: ReadJson

        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;
        }
开发者ID:olohmann,项目名称:Lohmann.HALight,代码行数:66,代码来源:ResourceConverter.cs

示例13: ReadJson

        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;
        }
开发者ID:justinoverton,项目名称:NeoApi,代码行数:87,代码来源:ColumnMappedArrayJsonConverter.cs

示例14: InitObject

        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));
        }
开发者ID:rischwa,项目名称:eve-fast-fitting-assessment,代码行数:8,代码来源:CrestJsonConverter.cs


注:本文中的Newtonsoft.Json.Linq.JObject.CreateReader方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。