本文整理汇总了C#中Newtonsoft.Json.JsonTextReader.ReadAsString方法的典型用法代码示例。如果您正苦于以下问题:C# JsonTextReader.ReadAsString方法的具体用法?C# JsonTextReader.ReadAsString怎么用?C# JsonTextReader.ReadAsString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Newtonsoft.Json.JsonTextReader
的用法示例。
在下文中一共展示了JsonTextReader.ReadAsString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: NewtonsoftDecode
private static string NewtonsoftDecode(string input)
{
var sr = new StringReader(input);
var reader = new JsonTextReader(sr);
var output = reader.ReadAsString();
reader.Close();
return output;
}
示例2: TestDecodeNamedEntities
public void TestDecodeNamedEntities ()
{
var path = Path.Combine ("..", "..", "TestData", "html", "HtmlEntities.json");
var decoder = new HtmlEntityDecoder ();
using (var json = new JsonTextReader (new StreamReader (path))) {
while (json.Read ()) {
string name, value;
if (json.TokenType == JsonToken.StartObject)
continue;
if (json.TokenType != JsonToken.PropertyName)
break;
name = (string) json.Value;
if (!json.Read () || json.TokenType != JsonToken.StartObject)
break;
// read to the "codepoints" property
if (!json.Read () || json.TokenType != JsonToken.PropertyName)
break;
// skip the array of integers...
if (!json.Read () || json.TokenType != JsonToken.StartArray)
break;
while (json.Read ()) {
if (json.TokenType == JsonToken.EndArray)
break;
}
// the property should be "characters" - this is what we want
if (!json.Read () || json.TokenType != JsonToken.PropertyName)
break;
value = json.ReadAsString ();
if (!json.Read () || json.TokenType != JsonToken.EndObject)
break;
for (int i = 0; i < name.Length && name[i] != ';'; i++)
Assert.IsTrue (decoder.Push (name[i]), "Failed to push char #{0} of \"{1}\".", i, name);
Assert.AreEqual (value, decoder.GetValue (), "Decoded entity did not match for \"{0}\".", name);
decoder.Reset ();
}
}
}
示例3: ReadConfidence
void ReadConfidence(JsonTextReader reader, Dictionary<string, double> wordConfidences)
{
reader.Read();
reader.Read();
if (reader.TokenType != JsonToken.EndArray) {
while (true) {
var wordText = reader.ReadAsString();
var conf = reader.ReadAsDouble();
wordConfidences[wordText] = conf.Value;
reader.Read();
var tok1 = reader.TokenType;
reader.Read();
var tok2 = reader.TokenType;
if (tok1 == JsonToken.EndArray && tok2 == JsonToken.EndArray) {
break;
}
}
}
}
示例4: _ParseJsonStation
/// <summary>
/// Returns an EliteStation from a EDDB Json Object.
/// JsonReader MUST currently point to the StartObject token for the Station object.
/// </summary>
/// <param name="jsonReader">JsonReader populated with the Station Object</param>
/// <returns>Populated EliteStation data</returns>
private EliteStation _ParseJsonStation(JsonTextReader jsonReader)
{
EliteStation es = new EliteStation();
if (jsonReader.TokenType != JsonToken.StartObject)
AerDebug.LogError("Malformed JSON parsing - _ParseJsonStation must be called on a StartObject token");
while(jsonReader.TokenType != JsonToken.EndObject)
{
jsonReader.Read();
switch(jsonReader.TokenType)
{
case JsonToken.PropertyName:
switch(jsonReader.Value.ToString())
{
case "id":
es.id = jsonReader.ReadAsInt32().GetValueOrDefault();
break;
case "name":
es.Name = jsonReader.ReadAsString();
break;
case "system_id":
es.System = GetSystem(jsonReader.ReadAsInt32().GetValueOrDefault());
break;
case "max_landing_pad_size":
es.MaxPadSize = jsonReader.ReadAsString();
break;
case "distance_to_star":
es.DistanceFromStar = jsonReader.ReadAsInt32().GetValueOrDefault();
break;
case "faction":
es.Faction = jsonReader.ReadAsString();
break;
case "government":
es.Government = jsonReader.ReadAsString();
break;
case "allegiance":
es.Allegiance = jsonReader.ReadAsString();
break;
case "state":
es.State = jsonReader.ReadAsString();
break;
case "type":
es.StarportType = jsonReader.ReadAsString();
break;
case "has_blackmarket":
es.HasBlackmarket = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_commodities":
es.HasCommodities = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_refuel":
es.HasRefuel = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_repear":
es.HasRepair = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_rearm":
es.HasRearm = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_outfitting":
es.HasOutfitting = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "has_shipyard":
es.HasShipyard = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1);
break;
case "import_commodities":
jsonReader.Read();
es.Imports = _ParseJsonCommodities(jsonReader);
break;
case "export_commodities":
jsonReader.Read();
es.Exports = _ParseJsonCommodities(jsonReader);
break;
case "prohibited_commodities":
jsonReader.Read();
es.Prohibited = _ParseJsonCommodities(jsonReader);
break;
case "economies":
jsonReader.Read();
es.Economies = _ParseJsonEconomies(jsonReader);
break;
case "updated_at":
es.UpdatedAt = jsonReader.ReadAsInt32().GetValueOrDefault();
break;
case "listings":
jsonReader.Read();
es.Listings = _ParseJsonListing(jsonReader);
break;
default:
break;
}
break;
case JsonToken.EndObject:
//.........这里部分代码省略.........
示例5: GetUserDataAsync
public async Task<bool> GetUserDataAsync()
{
IsLoading = true;
String strContent = await ViewModelLocator.Client.MakeOperationAsync(SupportedModules.USER,
SupportedMethods.GetUserData);
if (strContent != "")
{
User connectedUser = JsonConvert.DeserializeObject<User>(strContent);
StringReader str = new StringReader(strContent);
String institution = "";
String platform = "";
JsonTextReader reader = new JsonTextReader(str);
while (reader.Read())
{
if (reader.Value != null)
{
switch (reader.Value.ToString())
{
case "institutionName":
institution = reader.ReadAsString();
break;
case "platformName":
platform = reader.ReadAsString();
break;
default:
continue;
}
}
}
reader.Close();
str.Close();
Settings.UserSetting.setUser(connectedUser);
Settings.InstituteSetting = institution;
Settings.PlatformSetting = platform;
IsLoading = false;
return true;
}
IsLoading = false;
return false;
}
示例6: GetMonsterSprite
public Dictionary<int, string> GetMonsterSprite()
{
// 스프라이트 데이터 읽어오기
Dictionary<int, string> spriteNames = new Dictionary<int, string>();
try
{
string resourcePathTable = File.ReadAllText(Properties.Settings.Default.ResourcePathTablePath);
JsonTextReader reader = new JsonTextReader(new StringReader(resourcePathTable));
int key = 0;
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
if ((string)reader.Value == "Index")
{
key = Convert.ToInt32(reader.ReadAsInt32());
spriteNames.Add(key, null);
}
else if ((string)reader.Value == "Path")
spriteNames[key] = reader.ReadAsString();
}
}
}
catch (IOException ioe)
{
mInfoPath.resourcePathTable = false;
throw ioe;
}
catch (ArgumentException)
{
mInfoPath.resourcePathTable = false;
throw new IOException();
}
catch (Exception)
{
}
return spriteNames;
}
示例7: GetMonsterInfo
private void GetMonsterInfo(string stage, Dictionary<int, string> spriteNames, List<MonsterInfo> monsterInfos)
{
JsonTextReader reader;
MonsterInfo tmpInfo;
var monsterTable = "";
// 몬스터 데이터 읽어오기
if (stage == "Common")
monsterTable = File.ReadAllText(Path.Combine(Properties.Settings.Default.MonsterTablePath, Properties.Settings.Default.MonsterTableExportName + "_" + stage + ".json"));
else
monsterTable = File.ReadAllText(Path.Combine(Properties.Settings.Default.MonsterTablePath, Properties.Settings.Default.StageMonsterTablePath, Properties.Settings.Default.MonsterTableExportName + "_" + stage + ".json"));
/*JsonTextReader*/
reader = new JsonTextReader(new StringReader(monsterTable));
int cnt = 0;
/*MonsterInfo*/
tmpInfo = new MonsterInfo();
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
switch ((string)reader.Value)
{
case "Index":
if (cnt > 0)
monsterInfos.Add(tmpInfo);
cnt++;
tmpInfo.index = Convert.ToInt32(reader.ReadAsInt32());
break;
case "Stage":
tmpInfo.stage = reader.ReadAsString();
break;
case "Type":
try
{
tmpInfo.type = //reader.ReadAsString();
Enum.GetName(typeof(MonsterType), Convert.ToInt32(reader.ReadAsInt32()));
}
catch (ArgumentException)
{
tmpInfo.type = "NONE";
}
break;
case "Monster_Sprite":
int tmpIndex = Convert.ToInt32(reader.ReadAsInt32());
if (spriteNames.ContainsKey(tmpIndex))
tmpInfo.sprite = spriteNames[tmpIndex];
else
tmpInfo.sprite = "";
break;
case "MonsterExp":
tmpInfo.exp = Convert.ToInt32(reader.ReadAsInt32());
break;
case "MonsterPoint":
tmpInfo.point = Convert.ToInt32(reader.ReadAsInt32());
break;
case "MonsterMinGold":
tmpInfo.goldMin = Convert.ToInt32(reader.ReadAsInt32());
break;
case "MonsterMaxGold":
tmpInfo.goldMax = Convert.ToInt32(reader.ReadAsInt32());
break;
case "MonsterHP":
tmpInfo.HP = Convert.ToInt32(reader.ReadAsInt32());
break;
case "MonsterPAtk":
tmpInfo.atk = Convert.ToInt32(reader.ReadAsInt32());
break;
case "Speed":
tmpInfo.speed = Convert.ToDouble(reader.ReadAsString()) / Properties.Settings.Default.PermilFactor;
break;
case "MonsterScale":
tmpInfo.scale = Convert.ToDouble(reader.ReadAsString()) / Properties.Settings.Default.PermilFactor;
// 타입/스케일 정보로 색깔값 지정
tmpInfo.color = Globals.IG_PlanAddIn.GetMonsterTypeColor(tmpInfo.type, tmpInfo.scale);
break;
default:
break;
}
}
// 마지막 인덱스 몬스터 추가
if (tmpInfo.index > 0)
monsterInfos.Add(tmpInfo);
}
示例8: LoginUser
public void LoginUser(string username, string password)
{
string json = ParamsToJSON ("username", username, "password", password);
SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (LoginUserPath), json);
syrc.OnRestCallCompleted += (RestResult obj) =>
{
UserModel ret = null;
if (!obj.IsSuccess)
{
ret = new UserModel (obj.IsSuccess, obj.Result);
}
else
{
try
{
ret = new UserModel (true);
using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result)))
{
// JsonIndexer idx = new JsonIndexer (jtr);
// ret.DOBRaw = idx ["dob"];
// ret.EmailAddress = idx ["email"];
// ret.ID = idx ["id"];
// ret.LastName = idx ["lastName"];
while (jtr.Read())
{
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "email"))
{
ret.EmailAddress = jtr.ReadAsString ();
}
else
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "firstName"))
{
ret.FirstName = jtr.ReadAsString ();
}
else
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "lastName"))
{
ret.LastName = jtr.ReadAsString ();
}
else
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "id"))
{
ret.ID = jtr.ReadAsString ();
}
}
ret.InterestOne = SayHiBootStrapper.GenerateMockInterest ();
ret.InterestTwo = SayHiBootStrapper.GenerateMockInterest (ret.InterestOne ?? "");
}
}
catch (Exception e)
{
ret = new UserModel (false, GenerateParseErrorMessage (e));
}
}
SafeRaiseEvent (OnRegisterUserCompleted, ret);
};
syrc.SendRestRequest ();
}
示例9: NonAsciiStringEscapeHandling
public void NonAsciiStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
string unicode = "\u5f20";
writer.WriteValue(unicode);
string json = sw.ToString();
Assert.AreEqual(8, json.Length);
Assert.AreEqual(@"""\u5f20""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(unicode, reader.ReadAsString());
sw = new StringWriter();
writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.Default
};
writer.WriteValue(unicode);
json = sw.ToString();
Assert.AreEqual(3, json.Length);
Assert.AreEqual("\"\u5f20\"", json);
}
示例10: HtmlStringEscapeHandling
public void HtmlStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
string script = @"<script type=""text/javascript"">alert('hi');</script>";
writer.WriteValue(script);
string json = sw.ToString();
Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(script, reader.ReadAsString());
}
示例11: ReadAsString_BadData
public void ReadAsString_BadData()
{
string json = @"pie";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsString(); }, "Unexpected character encountered while parsing value: p. Path '', line 1, position 1.");
}
示例12: ReadAsString_Null_AdditionalBadData
public void ReadAsString_Null_AdditionalBadData()
{
string json = @"nullllll";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsString(); }, "Error parsing null value. Path '', line 1, position 4.");
}
示例13: Main
public static void Main (string[] args)
{
int maxEntityLength = 0;
int state = 0;
using (var json = new JsonTextReader (new StreamReader ("HtmlEntities.json"))) {
while (json.Read ()) {
string name, value;
if (json.TokenType == JsonToken.StartObject)
continue;
if (json.TokenType != JsonToken.PropertyName)
break;
name = (string) json.Value;
// trim leading '&' and trailing ';'
name = name.TrimStart ('&').TrimEnd (';');
if (!json.Read () || json.TokenType != JsonToken.StartObject)
break;
// read to the "codepoints" property
if (!json.Read () || json.TokenType != JsonToken.PropertyName)
break;
// skip the array of integers...
if (!json.Read () || json.TokenType != JsonToken.StartArray)
break;
while (json.Read ()) {
if (json.TokenType == JsonToken.EndArray)
break;
}
// the property should be "characters" - this is what we want
if (!json.Read () || json.TokenType != JsonToken.PropertyName)
break;
value = json.ReadAsString ();
var node = Root;
for (int i = 0; i < name.Length; i++) {
bool found = false;
for (int j = 0; j < node.Children.Count; j++) {
if (node.Children[j].Char == name[i]) {
node = node.Children[j];
found = true;
break;
}
}
if (!found) {
node = new GraphNode (node, ++state, name[i]);
continue;
}
}
if (node.Value == null) {
FinalStates.Add (node.State, node);
node.Value = value;
}
maxEntityLength = Math.Max (maxEntityLength, name.Length);
if (!json.Read () || json.TokenType != JsonToken.EndObject)
break;
}
}
using (var output = new StreamWriter ("HtmlEntityDecoder.g.cs")) {
output.WriteLine ("// WARNING: This file is auto-generated. DO NOT EDIT!");
output.WriteLine ();
output.WriteLine ("namespace HtmlKit {");
output.WriteLine ("\tpublic partial class HtmlEntityDecoder {");
output.WriteLine ("\t\tconst int MaxEntityLength = {0};", maxEntityLength);
output.WriteLine ();
GeneratePushNamedEntityMethod (output);
output.WriteLine ();
GenerateGetNamedEntityValueMethod (output);
output.WriteLine ("\t}");
output.WriteLine ("}");
}
}
示例14: RegisterUser
public void RegisterUser(string username, string password, string firstName, string lastName, string emailAddress, string dob = "",
string summary = "awesome summery", string interest1 = "", string interest2 = "", string interest3 = "")
{
string json = ParamsToJSON ("dob", dob, "summary", summary, "user", SayHiHelper.JSONBeginObject, "email", emailAddress,
"first_name", firstName, "last_name", lastName, "username", username, "password", password,
SayHiHelper.JSONEndObject);
SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (RegisterUserPath), json);
syrc.OnRestCallCompleted += (RestResult obj) =>
{
UserModel ret = null;
if (!obj.IsSuccess)
{
ret = new UserModel (obj.IsSuccess, obj.Result);
}
else
{
try
{
ret = new UserModel (true);
using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result)))
{
while (jtr.Read())
{
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "id"))
{
ret.ID = jtr.ReadAsString ();
break;//only parsing ID
}
}
}
//TODO:parse other fields
ret.FirstName = firstName;
ret.LastName = lastName;
ret.EmailAddress = emailAddress;
ret.DOBRaw = dob;
ret.Summary = summary;
ret.InterestOne = interest1;
ret.InterestTwo = interest2;
ret.InterestThree = interest3;
}
catch (Exception e)
{
ret = new UserModel (false, GenerateParseErrorMessage (e));
}
}
SafeRaiseEvent (OnRegisterUserCompleted, ret);
};
syrc.SendRestRequest ();
}
示例15: MatchUser
public void MatchUser(string userId, string eventCode)
{
string json = ParamsToJSON ("userid", userId, "event_code", eventCode);
SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (MatchUserPath), json);
syrc.OnRestCallCompleted += (RestResult obj) =>
{
UserModel ret = null;
if (!obj.IsSuccess)
{
ret = new UserModel (obj.IsSuccess, obj.Result);
}
else
{
try
{
ret = new UserModel (true);
using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result)))
{
while (jtr.Read())
{
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "matchName"))
{
string name = jtr.ReadAsString ();
if (name != null)
{
string[] vals = name.Split (' ');
ret.FirstName = vals [0];
if (vals.Length > 1)
{
ret.LastName = vals [1];
}
}
}
else
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "matchSummary"))
{
ret.Summary = jtr.ReadAsString ();
}
else
if (JsonKeyMatches (jtr, JsonToken.PropertyName, "username"))
{
ret.Summary = jtr.ReadAsString ();
}
}
ret.InterestOne = SayHiBootStrapper.GenerateMockInterest ();
ret.InterestTwo = SayHiBootStrapper.GenerateMockInterest (ret.InterestOne);
}
}
catch (Exception e)
{
ret = new UserModel (false, GenerateParseErrorMessage (e));
}
}
SafeRaiseEvent (OnMatchUserCompleted, ret);
};
syrc.SendRestRequest ();
}