本文整理汇总了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();
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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);
});
}
示例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;
}
示例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);
}
}
示例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;
}
示例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;
}
示例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'.");
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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);
}