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


C# Linq.JTokenReader类代码示例

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


JTokenReader类属于Newtonsoft.Json.Linq命名空间,在下文中一共展示了JTokenReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WriteJson

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var pair = (SwaggerOperationsExtended)value;

            writer.WriteStartObject();
            var count = pair.Keys.Count;
            for (var i = 0; i < count; i++)
            {
                var key = pair.Keys.ElementAt(i);
                var oVal = pair.Values.ElementAt(i);
                
                writer.WritePropertyName(key.ToString().ToLower());

                var tokenReader = new JTokenReader(JToken.FromObject(oVal));
                writer.WriteToken(tokenReader);
            }
            writer.WriteEndObject();
        }
开发者ID:TiandaoStudy,项目名称:Abp.Swagger.Example,代码行数:18,代码来源:SwaggerOperationsExtendedConverter.cs

示例2: ReadJson

		public override object ReadJson (Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var store = (PropertyStore)existingValue;
			var items = JToken.ReadFrom (reader);

			foreach (var item in items)
			{
				var typeName = (string)item["$type"];
				if (typeName != null) {

					var type = ((EtoBinder)serializer.Binder).BindToType (typeName);
					if (type != null) {
						foreach (var prop in (IDictionary<string, JToken>)item) {
							if (prop.Key == "$type") continue;
							var memberName = "Set" + prop.Key;
							var member = type.GetRuntimeMethods().FirstOrDefault(r => r.IsStatic && r.Name == memberName);
							if (member == null)
								throw new JsonSerializationException(string.Format(CultureInfo.CurrentCulture, "Could not find attachable property {0}.{1}", type.Name, memberName));
							var parameters = member.GetParameters();
							if (parameters.Length != 2)
								throw new JsonSerializationException(string.Format(CultureInfo.CurrentCulture, "Invalid number of parameters"));
							var propType = parameters[1].ParameterType;
							using (var propReader = new JTokenReader(prop.Value)) {
								var propValue = serializer.Deserialize(propReader, propType);
								member.Invoke (null, new object[] { store.Parent, propValue });
							}
						}
					}
				}
			}
			return existingValue;
		}
开发者ID:mhusen,项目名称:Eto,代码行数:32,代码来源:PropertyStoreConverter.cs

示例3: ReadJson

		public override object ReadJson (Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var store = existingValue as PropertyStore;
			var items = JArray.ReadFrom (reader);

			foreach (var item in (IEnumerable<JToken>)items)
			{
				var typeName = (string)item["$type"];
				if (typeName != null) {

					var type = ((EtoBinder)serializer.Binder).BindToType (typeName);
					if (type != null) {
						foreach (var prop in (IDictionary<string, JToken>)item) {
							if (prop.Key == "$type") continue;
							var memberName = "Set" + prop.Key;
							var member = type.GetMethod(memberName, BindingFlags.Static | BindingFlags.Public);
							if (member == null)
								throw new JsonSerializationException(string.Format ("Could not find attachable property {0}.{1}", type.Name, memberName));
							var parameters = member.GetParameters();
							if (parameters.Length != 2)
								throw new JsonSerializationException("Invalid number of parameters");
							var propType = parameters[1].ParameterType;
							using (var propReader = new JTokenReader(prop.Value)) {
								var propValue = serializer.Deserialize(propReader, propType);
								member.Invoke (null, new object[] { store.Parent, propValue });
							}
						}
					}
				}
			}
			return existingValue;
		}
开发者ID:majorsilence,项目名称:Eto,代码行数:32,代码来源:PropertyStoreConverter.cs

示例4: ToObject

 public static object ToObject(this JToken token, Type targetType, JsonSerializerSettings settings)
 {
     var jsonSerializer = JsonSerializer.Create(settings);
     using (var jtokenReader = new JTokenReader(token))
     {
         return jsonSerializer.Deserialize(jtokenReader, targetType);
     }
 }
开发者ID:mcintyre321,项目名称:Sourcery,代码行数:8,代码来源:JTokenExtension.cs

示例5: ConvertTo

 public object ConvertTo(Type type)
 {
     // A non generic implementation of ToObject<T> on JToken
     using (var jsonReader = new JTokenReader(_value))
     {
         var serializer = new JsonSerializer();
         return serializer.Deserialize(jsonReader, type);
     }
 }
开发者ID:Kazzje,项目名称:SignalR,代码行数:9,代码来源:JTokenValue.cs

示例6: SearchUser

		public Task<IEnumerable<User>> SearchUser(string username)
		{
			return this.GetDynamicAsync(string.Format("/search/users?q={0}", username)).ContinueWith(t =>
				{
					var serializer = JsonSerializer.Create(new JsonSerializerSettings());
					var users = ((JObject)t.Result)["items"];
					var reader = new JTokenReader(users);
					return serializer.Deserialize<IEnumerable<User>>(reader);
				});
		}
开发者ID:Icenium,项目名称:Github.Api,代码行数:10,代码来源:UserApi.cs

示例7: ReadJson

        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            var result = new Document();
            JObject bag = serializer.Deserialize<JObject>(reader);

            foreach (JProperty field in bag.Properties())
            {
                // Skip OData @search annotations. These are deserialized separately.
                if (field.Name.StartsWith("@search.", StringComparison.Ordinal))
                {
                    continue;
                }

                object value;
                if (field.Value == null)
                {
                    value = null;
                }
                else if (field.Value is JArray)
                {
                    JArray array = (JArray)field.Value;

                    if (array.Count == 0)
                    {
                        // Assume string arrays for now.
                        value = EmptyStringArray;
                    }
                    else
                    {
                        value = array.Select(t => t.Value<string>()).ToArray();
                    }
                }
                else if (field.Value is JObject)
                {
                    var tokenReader = new JTokenReader(field.Value);
                    
                    // Assume GeoPoint for now.
                    value = serializer.Deserialize<GeographyPoint>(tokenReader);
                }
                else
                {
                    value = field.Value.ToObject(typeof(object), serializer);
                }

                result[field.Name] = value;
            }

            return result;
        }
开发者ID:theadriangreen,项目名称:azure-sdk-for-net,代码行数:53,代码来源:DocumentConverter.cs

示例8: ResolveParameter

        /// <summary>
        /// Resolves a parameter value based on the provided object.
        /// </summary>
        /// <param name="descriptor">Parameter descriptor.</param>
        /// <param name="value">Value to resolve the parameter value from.</param>
        /// <returns>The parameter value.</returns>
        public virtual object ResolveParameter(ParameterDescriptor descriptor, JToken value)
        {
            if (value.GetType() == descriptor.Type)
            {
                return value;
            }

            // A non generic implementation of ToObject<T> on JToken
            using (var jsonReader = new JTokenReader(value))
            {
                var serializer = new JsonSerializer();
                return serializer.Deserialize(jsonReader, descriptor.Type);
            }
        }
开发者ID:nightbob3,项目名称:SignalR,代码行数:20,代码来源:DefaultParameterResolver.cs

示例9: Deserialize

        public IList<object> Deserialize(object json)
        {
            JArray data;
            if (json is string)
            {
                data = JArray.Parse((string)json);
            }
            else if (json is JArray)
                data = (JArray)json;
            else
                throw new DextopException();

            var result = new List<object>();
            foreach (var o in data)
                using (var reader = new JTokenReader(o))
                    result.Add(DextopUtil.JsonSerializer.Deserialize(reader, Meta.ModelType));

            return result;
        }
开发者ID:borisdj,项目名称:dextop,代码行数:19,代码来源:DextopModel.Serializer.Json.cs

示例10: GetCharacterFromSource

        /// <summary>
        ///     Extrae un personaje de la fuente de datos en JSON.
        /// </summary>
        /// <param name="name">
        ///     El nombre del pesonaje a extraer de la fuente de datos.
        /// </param>
        /// <returns>
        ///     Un objeto Character cuyo nombre coincide con el solicitado.
        /// </returns>
        /// <pre>true</pre>
        /// <post>(this.Contains(name) => (returnValue != null) && (returnValue.Name.Equals(name)))</post>
        public FullCharacter GetCharacterFromSource(string name)
        {
            FullCharacter character = null;

            // Obtenemos un lector de tokens de Json. Para ello creamos primero un stream de la
            // cadena json, luego creamos un lector de texto usando ese stream y por último creamos
            // un lector de tokens utilizando el lector de texto y lo inicializamos
            JsonReader reader = new JsonTextReader(new StringReader(jsonString));
            JTokenReader tokenreader = new JTokenReader(JToken.ReadFrom(reader));
            tokenreader.Read();

            // Obtenemos el token cuyo nombre corresponde al deseado, utilizando para ello una
            // expresión JSonPath
            // Para más información sobre JPath: http://goessner.net/articles/JsonPath/
            JToken token = tokenreader.CurrentToken.SelectToken("$.[?(@.name=='" + name + "')]", false);

            // Si existe un token con dihco nombre, existe el personaje buscado
            if (token != null)
            {
                // Creamos un nuevo objeto de tipo Character e incrementamos el correspondiente
                // contador
                character = new FullCharacter();
                createdCharacters++;

                // Extraemos el valor de la Propiedad Nombre del correspondiente token
                character.Name = token.SelectToken("name").Value<String>();

                // Extraemos el valor de la Propiedad Nombre del correspondiente token
                character.Description = token.SelectToken("description").Value<String>();
                IEnumerable<JToken> relatedCharactersTokens = token.SelectToken("related_characters").Values<JToken>();

                // Construimos la colección de personajes relacionados con la colección de tokens JSON
                FillRelatedCharacters(character, relatedCharactersTokens);
            } // if

            // Cerramos los lectores que estén abiertos
            tokenreader.Close();
            reader.Close();

            return character;
        }
开发者ID:algorri94,项目名称:dissoftware,代码行数:52,代码来源:GetJsonService.cs

示例11: ReadBytesFailure

        public void ReadBytesFailure()
        {
            ExceptionAssert.Throws<JsonReaderException>(() =>
            {
                JObject o =
                    new JObject(
                        new JProperty("Test1", 1)
                        );

                using (JTokenReader jsonReader = new JTokenReader(o))
                {
                    jsonReader.Read();
                    Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);

                    jsonReader.Read();
                    Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                    Assert.AreEqual("Test1", jsonReader.Value);

                    jsonReader.ReadAsBytes();
                }
            }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'.");
        }
开发者ID:michal2229,项目名称:cs-json-dane-pogodowe-openweathermap,代码行数:22,代码来源:JTokenReaderTest.cs

示例12: ToDataTable

 public DataTable ToDataTable(JToken token)
 {
     if (!(token is JArray))
     {
         JArray container = new JArray();
         container.Add(token);
         token = container;
     }
     JTokenReader reader = new JTokenReader(token);
     JsonSerializer serializer = new JsonSerializer();
     serializer.Converters.Add(new DataTableConverter());
     DataTable dataTable = serializer.Deserialize<DataTable>(reader);
     if (!dataTable.Columns.Contains("crmid"))
     {
         dataTable.Columns.Add("crmid", typeof(int));
         foreach (DataRow row in dataTable.Rows)
         {
             row["crmid"] = ToCrmId(row["id"].ToString());
         }
         dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["crmid"] };
     }
     return dataTable;
 }
开发者ID:MetricWise,项目名称:vtwsclib.NET,代码行数:23,代码来源:WebServiceDataAdapter.cs

示例13: ReadBytes

        public void ReadBytes()
        {
            byte[] data = Encoding.UTF8.GetBytes("Hello world!");

            JObject o =
                new JObject(
                    new JProperty("Test1", data)
                    );

            using (JTokenReader jsonReader = new JTokenReader(o))
            {
                jsonReader.Read();
                Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test1", jsonReader.Value);

                byte[] readBytes = jsonReader.ReadAsBytes();
                Assert.AreEqual(data, readBytes);

                Assert.IsTrue(jsonReader.Read());
                Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType);

                Assert.IsFalse(jsonReader.Read());
                Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
            }
        }
开发者ID:michal2229,项目名称:cs-json-dane-pogodowe-openweathermap,代码行数:28,代码来源:JTokenReaderTest.cs

示例14: Should_be_able_to_suck_out_an_object

        public void Should_be_able_to_suck_out_an_object()
        {
            Envelope result;
            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false))
            using (var reader = new StreamReader(memoryStream))
            using (var jsonReader = new JsonTextReader(reader))
            {
                result = _deserializer.Deserialize<Envelope>(jsonReader);
            }

            using (var jsonReader = new JTokenReader(result.Message as JToken))
            {
                var message = (TestMessage)_serializer.Deserialize(jsonReader, typeof(TestMessage));

                message.Name.ShouldBe("Joe");
                message.Details.Count.ShouldBe(2);
            }
        }
开发者ID:MassTransit,项目名称:MassTransit,代码行数:18,代码来源:JsonSerialization_Specs.cs

示例15: DeserializeFromRaw

    public void DeserializeFromRaw()
    {
      PersonRaw raw = new PersonRaw
      {
        FirstName = "FirstNameValue",
        RawContent = new JRaw("[1,2,3,4,5]"),
        LastName = "LastNameValue"
      };

      JObject o = JObject.FromObject(raw);

      JsonReader reader = new JTokenReader(o);
      JsonSerializer serializer = new JsonSerializer();
      raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));

      Assert.AreEqual("FirstNameValue", raw.FirstName);
      Assert.AreEqual("LastNameValue", raw.LastName);
      Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
    }
开发者ID:Jessecar96,项目名称:Newtonsoft.Json,代码行数:19,代码来源:JObjectTests.cs


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