本文整理汇总了C#中Raven.Imports.Newtonsoft.Json.JsonTextReader类的典型用法代码示例。如果您正苦于以下问题:C# JsonTextReader类的具体用法?C# JsonTextReader怎么用?C# JsonTextReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonTextReader类属于Raven.Imports.Newtonsoft.Json命名空间,在下文中一共展示了JsonTextReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParseAndValidate
private static void ParseAndValidate(string text, int expectedLength)
{
var reader = new StringReader(text);
var jsonTextReader = new JsonTextReader(reader);
Assert.True(jsonTextReader.Read());
Assert.Equal(JsonToken.StartObject, jsonTextReader.TokenType);
Assert.True(jsonTextReader.Read());
Assert.Equal(JsonToken.PropertyName, jsonTextReader.TokenType);
Assert.Equal("Data", jsonTextReader.Value);
var memoryStream = jsonTextReader.ReadBytesAsStream();
Assert.Equal(expectedLength, memoryStream.Length);
Assert.True(jsonTextReader.Read());
Assert.Equal(JsonToken.PropertyName, jsonTextReader.TokenType);
Assert.Equal("Metadata", jsonTextReader.Value);
Assert.True(jsonTextReader.Read());
Assert.Equal(JsonToken.Null, jsonTextReader.TokenType);
Assert.True(jsonTextReader.Read());
Assert.Equal(JsonToken.EndObject, jsonTextReader.TokenType);
Assert.False(jsonTextReader.Read());
}
示例2: FloatParseHandling
public void FloatParseHandling()
{
string json = "[1.0,1,9.9,1E-06]";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
reader.FloatParseHandling = Json.FloatParseHandling.Decimal;
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(1.0m, reader.Value);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(1L, reader.Value);
Assert.AreEqual(typeof(long), reader.ValueType);
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(9.9m, reader.Value);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(Convert.ToDecimal(1E-06), reader.Value);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
}
示例3: Deserialize
public virtual object Deserialize(Stream stream, System.Type type)
{
using (StreamReader r = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(r))
using (RavenJTokenReader tokenReader = new RavenJTokenReader(RavenJToken.ReadFrom(jsonReader)))
{
return serializer.Deserialize(tokenReader, type);
}
}
示例4: CanDeserialiseNullableStruct
public void CanDeserialiseNullableStruct()
{
var reader = new JsonTextReader(new StringReader("{\"Value\":{\"X\":\"Bob\"}}"));
var i2 = _serialiser.Deserialize<C>(reader);
Assert.That(i2, Is.Not.Null);
Assert.That(i2.Value, Is.Not.Null);
Assert.That(((D)i2.Value).X, Is.EqualTo("Bob"));
}
示例5: Import
public DumperStats Import(string file)
{
var stopwatch = Stopwatch.StartNew();
using (var streamReader =
new StreamReader(new GZipStream(File.OpenRead(file), CompressionMode.Decompress)))
{
var jsonReader = new JsonTextReader(streamReader);
if (jsonReader.Read() == false)
return new DumperStats();
if (jsonReader.TokenType != JsonToken.StartObject)
throw new InvalidDataException("StartObject was expected");
var indexes = new Dictionary<string, IndexDefinition>();
var indexCount = 0;
Read(jsonReader,
"Indexes",
index =>
{
indexCount++;
var indexName = index.Value<string>("name");
if (!indexName.StartsWith("Raven/"))
{
indexes[indexName] = index.Value<RavenJObject>("definition").JsonDeserialization<IndexDefinition>();
}
});
foreach (var index in indexes)
{
_documentDatabase.PutIndex(index.Key, index.Value);
}
var total = 0;
var batch = new List<RavenJObject>();
Read(jsonReader,
"Docs",
document =>
{
total++;
batch.Add((RavenJObject)document);
if (batch.Count >= 128)
{
FlushBatch(batch);
}
});
FlushBatch(batch);
stopwatch.Stop();
return new DumperStats
{
Attachments = 0,
Documents = total,
Indexes = indexCount,
Elapsed = stopwatch.Elapsed
};
}
}
示例6: ImportJobs
public void ImportJobs(string jobsJson)
{
var serializer = this.DocumentSession.Advanced.DocumentStore.Conventions.CreateSerializer();
using (var reader = new StringReader(jobsJson))
using (var jsonReader = new JsonTextReader(reader))
{
var data = serializer.Deserialize<List<JobDefinition>>(jsonReader);
this.JobManager.ImportJobs(data);
}
}
示例7: Can_read_date_time_offset_from_lucene_query
public void Can_read_date_time_offset_from_lucene_query()
{
var jsonSerializer = new DocumentConvention().CreateSerializer();
using (var reader = new JsonTextReader(new StringReader(@"{""Item"": ""20090402193554412""}")))
{
var deserialize = jsonSerializer.Deserialize<Test>(reader);
Assert.Equal(2009, deserialize.Item.Year);
}
}
示例8: ReadSingleQuoteInsideDoubleQuoteString
public void ReadSingleQuoteInsideDoubleQuoteString()
{
string json = @"{""NameOfStore"":""Forest's Bakery And Cafe""}";
JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json));
jsonTextReader.Read();
jsonTextReader.Read();
jsonTextReader.Read();
Assert.AreEqual(@"Forest's Bakery And Cafe", jsonTextReader.Value);
}
示例9: CanDeserialiseInheritedObject
public void CanDeserialiseInheritedObject()
{
var item = new A() { Name = "B", Children = new List<A>() { new B() { Id = 10, Name = "Child B", }, new A { Name = "Child A" } } };
var json = new StringWriter();
_serialiser.Serialize(json, item);
var reader = new JsonTextReader(new StringReader(json.ToString()));
var b = _serialiser.Deserialize<A>(reader);
Assert.That(b.Children.First(), Is.InstanceOf<B>());
Assert.That(((B)b.Children.First()).Id, Is.EqualTo(10));
}
示例10: ReadMultilineString
public void ReadMultilineString()
{
string json = @"""first line
second line
third line""";
JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(jsonTextReader.Read());
Assert.AreEqual(JsonToken.String, jsonTextReader.TokenType);
Assert.AreEqual(@"first line
second line
third line", jsonTextReader.Value);
}
示例11: Import
public ActionResult Import(HttpPostedFileBase fileData)
{
string fileString = StreamHelper.ReadAll(fileData.InputStream);
var serializer = this.DocumentSession.Advanced.DocumentStore.Conventions.CreateSerializer();
using (var streamReader = new StreamReader(fileData.InputStream))
{
using (var jsonReader = new JsonTextReader(streamReader))
{
var data = serializer.Deserialize<ImportExportFile>(jsonReader);
this.JobManager.ImportJobs(data.JobDefinitionList);
this.SettingsManager.ImportSettings(data.SettingsContainerList);
return RedirectToAction("ImportComplete");
}
}
}
示例12: SurrogatePairValid
public void SurrogatePairValid()
{
string json = @"{ ""MATHEMATICAL ITALIC CAPITAL ALPHA"": ""\uD835\uDEE2"" }";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
string s = reader.Value.ToString();
Assert.AreEqual(2, s.Length);
StringInfo stringInfo = new StringInfo(s);
Assert.AreEqual(1, stringInfo.LengthInTextElements);
}
示例13: Non_existing_data_folder_should_throw_proper_exception
public async Task Non_existing_data_folder_should_throw_proper_exception()
{
using (var store = NewStore(requestedStorage: "voron", runInMemory: true))
{
using (var session = store.OpenAsyncSession())
{
session.RegisterUpload("test.file", new MemoryStream(new byte[] { 1, 2, 3 }));
await session.SaveChangesAsync();
}
await store.AsyncFilesCommands.Admin.StartBackup(backupLocation,
null, false, store.DefaultFileSystem);
WaitForBackup(store.AsyncFilesCommands, true);
FileSystemDocument document;
using (var file = File.OpenText(Path.Combine(backupLocation, Constants.FilesystemDocumentFilename)))
using (var reader = new JsonTextReader(file))
document = (new JsonSerializer()).Deserialize<FileSystemDocument>(reader);
var drives = DriveInfo.GetDrives().Select(x => x.Name.ToLower()[0]).ToArray();
var lastDriveLetter = 'a';
while (lastDriveLetter != 'z')
{
if (drives.Contains(lastDriveLetter) == false)
break;
lastDriveLetter++;
}
document.Settings[Constants.FileSystem.DataDirectory] = string.Format("{0}:\\", (char)(lastDriveLetter )); //on purpose, non existing path
using (var file = File.CreateText(Path.Combine(backupLocation, Constants.FilesystemDocumentFilename)))
using (var writer = new JsonTextWriter(file))
(new JsonSerializer()).Serialize(writer, document);
Assert.Throws<BadRequestException>(() =>
AsyncHelpers.RunSync(() => store.AsyncFilesCommands.Admin.StartRestore(new FilesystemRestoreRequest
{
BackupLocation = backupLocation
})));
}
}
示例14: Execute
public override void Execute(object parameter)
{
if (string.IsNullOrWhiteSpace(queryModel.Address))
return;
var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + Uri.EscapeUriString(queryModel.Address) +
"&key=Anlj2YMQu676uXmSj1QTSni66f8DjuBGToZ21t5z9E__lL8IHRhFP8LtF7umitL6";
var webRequest = WebRequest.Create(new Uri(url, UriKind.Absolute));
webRequest.GetResponseAsync().ContinueOnSuccessInTheUIThread(doc =>
{
RavenJObject jsonData;
using (var stream = doc.GetResponseStream())
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
jsonData = RavenJObject.Load(jsonReader);
var set = jsonData["resourceSets"];
var item = set.Values().First().Values().ToList()[1].Values().ToList();
if (item.Count == 0)
{
ApplicationModel.Current.AddInfoNotification("Could not calculate the given address");
return;
}
var result = item.First().SelectToken("point").SelectToken("coordinates").Values().ToList();
if (result != null)
{
var latitude = double.Parse(result[0].ToString());
var longitude = double.Parse(result[1].ToString());
var addressData = new AddressData { Address = queryModel.Address, Latitude = latitude, Longitude = longitude };
queryModel.UpdateResultsFromCalculate(addressData);
}
}).Catch();
}
示例15: ReadSingleValueAsStreamShouldWork
public void ReadSingleValueAsStreamShouldWork(int size)
{
var random = new Random(size);
var buffer = new byte[size];
random.NextBytes(buffer);
var d = new Data
{
Foo = buffer
};
var jsonObj = RavenJToken.FromObject(d);
var jsonObjAsString = jsonObj.ToString();
using (var textReader = new StringReader(jsonObjAsString))
using (var jsonReader = new JsonTextReader(textReader))
{
jsonReader.Read(); // start object
jsonReader.Read(); // property name
var actual = new byte[buffer.Length];
using (var objectStream = jsonReader.ReadBytesAsStream())
{
objectStream.Read(actual, 0, actual.Length);
for (int a = 0; a < actual.Length; a++)
{
if (buffer[a] != actual[a])
{
Assert.True(false, "not equal on byte " + a);
}
}
}
}
}