protected override async Task ProcessRequestCoreAsync(HttpContext ctx, string viewer, string world, long startTime) { var req = ctx.Request; var resp = ctx.Response; if(!req.IsAuthenticated) { resp.StatusCode = 403; return; } var currentTs = Utils.UnixTimestamp.CurrentMillisecondTimestamp; var start2Ts = start2Timestamp; if((currentTs - startTime < Start2ValidityPeriod) && (currentTs - start2Ts > Start2ValidityPeriod)) { string referer = null; if(req.Headers["Referer"] != null) { var hdrLine = req.Headers["Referer"]; var schema = hdrLine.IndexOf("//") + 2; var kcsUrl = hdrLine.IndexOf("/kcs", schema); if(kcsUrl > 0) { referer = world + hdrLine.Substring(kcsUrl + 1); } } var proxyResponse = await Utils.Forwarder.ForwardRequest(req, world + "kcsapi/api_start2", referer); if(proxyResponse != null) { using(proxyResponse) { if(proxyResponse.StatusCode == HttpStatusCode.OK) { string newStart2; using(StreamReader rdr = new StreamReader(proxyResponse.GetResponseStream())) { newStart2 = (await rdr.ReadToEndAsync()); } JsonReader json = new JsonTextReader(new StringReader(newStart2.Substring(7))); while(json.Read()) { if(json.TokenType == JsonToken.PropertyName && json.Value.ToString() == "api_result") { if(json.ReadAsInt32() == 1) { if(System.Threading.Interlocked.CompareExchange(ref start2Timestamp, currentTs, start2Ts) == start2Ts) { start2Content = newStart2; File.WriteAllText(ctx.Server.MapPath("~/App_Data/api_start2.json"), start2Content); } } break; } } } } } } if(start2Content == null) { ctx.Response.StatusCode = 503; return; } ctx.Response.ContentType = "text/plain"; ctx.Response.Write(start2Content); return; }
public void Read(JsonTextReader reader) { Regions.Clear(); if ( !reader.ReadStartObject() ) return; if ( reader.ReadPropertyName() != "regions" ) return; if ( !reader.ReadStartArray() ) return; while ( reader.ReadStartObject() ) { if ( reader.ReadPropertyName() != "start" ) break; int start = reader.ReadAsInt32().Value; if ( reader.ReadPropertyName() != "length" ) break; int end = reader.ReadAsInt32().Value; reader.ReadEndObject(); Tuple<int, int> region = new Tuple<int,int>(start, end); Regions.Add(region); } }
public void ReadInvalidNonBase10Number() { string json = "0aq2dun13.hod"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid number. Path '', line 1, position 2.", () => { reader.Read(); }); reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid decimal. Path '', line 1, position 2.", () => { reader.ReadAsDecimal(); }); reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid integer. Path '', line 1, position 2.", () => { reader.ReadAsInt32(); }); }
private bool TryParseNetworkMessage(string messageText, out INetworkMessage message) { /* Let's assume message structure is: * { * messagetype: short, * version: byte, * payload: { * * serialised form of message payload type * } */ short messageType = 0; byte version = 0; long? correlationId = null; JObject payloadJson = null; message = null; using (var text = new StringReader(messageText)) using (var reader = new JsonTextReader(text) {CloseInput = true}) { while (reader.Read()) { if (reader.Value == null || reader.TokenType != JsonToken.PropertyName) continue; var propertyName = reader.Value.ToString(); switch (propertyName) { case "messageType": messageType = (short)(reader.ReadAsInt32() ?? 0); if (messageType == 0) return false; break; case "version": version = (byte)(reader.ReadAsInt32() ?? 0); if (version == 0) return false; break; case "correlationId": var correlationAsDecimal = reader.ReadAsDecimal(); if (correlationAsDecimal.HasValue) correlationId = (long)correlationAsDecimal.Value; break; case "payload": reader.Read(); // todo: better solution to this??? payloadJson = JObject.Load(reader); break; default: return false; } } } if (messageType == 0 || version == 0 || payloadJson == null) return false; var payloadRegistration = MessageFactory.GetPayloadRegistration(messageType, version); message = payloadRegistration.CreateMessage( correlationId, (MessagePayload)serializer.Deserialize( payloadJson.CreateReader(), payloadRegistration.PayloadType)); return true; }
public void ReadAsIntDecimal() { string json = @"{""Name"": 1.1}"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<FormatException>( "Input string was not in a correct format.", () => { reader.ReadAsInt32(); }); }
public void ParseIntegers() { JsonTextReader reader = null; reader = new JsonTextReader(new StringReader("1")); Assert.AreEqual(1, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-1")); Assert.AreEqual(-1, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("0")); Assert.AreEqual(0, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-0")); Assert.AreEqual(0, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(int.MaxValue.ToString())); Assert.AreEqual(int.MaxValue, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(int.MinValue.ToString())); Assert.AreEqual(int.MinValue, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(long.MaxValue.ToString())); ExceptionAssert.Throws<OverflowException>("Arithmetic operation resulted in an overflow.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd")); ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("1E-06")); ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("1.1")); ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("")); Assert.AreEqual(null, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-")); ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32()); }
public void ReadInt32Overflow() { long i = int.MaxValue; JsonTextReader reader = new JsonTextReader(new StringReader(i.ToString(CultureInfo.InvariantCulture))); reader.Read(); Assert.AreEqual(typeof(long), reader.ValueType); for (int j = 1; j < 1000; j++) { long total = j + i; ExceptionAssert.Throws<JsonReaderException>( "JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 10.", () => { reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture))); reader.ReadAsInt32(); }); } }
public void ReadInvalidNonBase10Number() { string json = "0aq2dun13.hod"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.", () => { reader.Read(); }); reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.", () => { reader.ReadAsDecimal(); }); reader = new JsonTextReader(new StringReader(json)); ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.", () => { reader.ReadAsInt32(); }); }
public void ReadIntegerWithErrorInArray() { string json = @"[ 333333333333333333333333333333333333333, 3.3, , 0f ]"; JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.StartArray, jsonTextReader.TokenType); ExceptionAssert.Throws<JsonReaderException>( "JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path '[0]', line 2, position 42.", () => jsonTextReader.ReadAsInt32()); ExceptionAssert.Throws<JsonReaderException>( "Input string '3.3' is not a valid integer. Path '[1]', line 3, position 6.", () => jsonTextReader.ReadAsInt32()); ExceptionAssert.Throws<JsonReaderException>( "Error reading integer. Unexpected token: Undefined. Path '[2]', line 4, position 3.", () => jsonTextReader.ReadAsInt32()); ExceptionAssert.Throws<JsonReaderException>( "Input string '0f' is not a valid integer. Path '[3]', line 5, position 5.", () => jsonTextReader.ReadAsInt32()); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.EndArray, jsonTextReader.TokenType); Assert.IsFalse(jsonTextReader.Read()); }
public void ReadStringValue_CommaErrors_Multiple() { JsonTextReader reader = new JsonTextReader(new StringReader("['',,'']")); reader.Read(); reader.ReadAsInt32(); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsString(); }, "Unexpected character encountered while parsing value: ,. Path '[1]', line 1, position 5."); Assert.AreEqual(string.Empty, reader.ReadAsString()); Assert.IsTrue(reader.Read()); }
public void ReadNumberValue_InvalidEndArray() { JsonTextReader reader = new JsonTextReader(new StringReader("]")); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Unexpected character encountered while parsing value: ]. Path '', line 1, position 1."); }
public void ReadNumberValue_CommaErrors() { JsonTextReader reader = new JsonTextReader(new StringReader("[,1]")); reader.Read(); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Unexpected character encountered while parsing value: ,. Path '[0]', line 1, position 2."); Assert.AreEqual(1, reader.ReadAsInt32()); Assert.IsTrue(reader.Read()); }
public void ReadInt32WithBadCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"true")); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Unexpected character encountered while parsing value: t. Path '', line 1, position 1."); }
public void ReadIntegerWithErrorInArray() { string json = @"[ 333333333333333333333333333333333333333, 3.3, , 0f ]"; JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.StartArray, jsonTextReader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path '[0]', line 2, position 41."); ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Input string '3.3' is not a valid integer. Path '[1]', line 3, position 5."); ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Unexpected character encountered while parsing value: ,. Path '[2]', line 4, position 3."); ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Input string '0f' is not a valid integer. Path '[3]', line 5, position 4."); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.EndArray, jsonTextReader.TokenType); Assert.IsFalse(jsonTextReader.Read()); }
public static ApiResponse ParseJsonResponse(Stream stream) { using (var jsonReader = new JsonTextReader(new StreamReader(stream))) { var apiResponse = new ApiResponse(); while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.PropertyName) { switch ((string)jsonReader.Value) { case "statusCode": apiResponse.StatusCode = jsonReader.ReadAsInt32() ?? 0; break; case "count": apiResponse.Count = jsonReader.ReadAsInt32() ?? 0; break; case "response": apiResponse.Response = jsonReader.GetInnerJson(); break; case "error": jsonReader.Read(); throw ParseError(jsonReader); default: jsonReader.Skip(); break; } } } return apiResponse; } }
public void ReadIntegerWithError() { string json = @"{ ChildId: 333333333333333333333333333333333333333 }"; JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.StartObject, jsonTextReader.TokenType); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType); ExceptionAssert.Throws<JsonReaderException>( "JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path 'ChildId', line 2, position 53.", () => jsonTextReader.ReadAsInt32()); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType); Assert.IsFalse(jsonTextReader.Read()); }
public void ReadStringValue_Numbers_NotString() { JsonTextReader reader = new JsonTextReader(new StringReader("[56,56]")); reader.Read(); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTime(); }, "Unexpected character encountered while parsing value: 5. Path '', line 1, position 2."); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTime(); }, "Unexpected character encountered while parsing value: 6. Path '', line 1, position 3."); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTime(); }, "Unexpected character encountered while parsing value: ,. Path '[0]', line 1, position 4."); Assert.AreEqual(56, reader.ReadAsInt32()); Assert.IsTrue(reader.Read()); }
public void ParseIntegers() { JsonTextReader reader = null; reader = new JsonTextReader(new StringReader("1")); Assert.AreEqual(1, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-1")); Assert.AreEqual(-1, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("0")); Assert.AreEqual(0, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-0")); Assert.AreEqual(0, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(int.MaxValue.ToString())); Assert.AreEqual(int.MaxValue, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(int.MinValue.ToString())); Assert.AreEqual(int.MinValue, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(long.MaxValue.ToString())); ExceptionAssert.Throws<JsonReaderException>("JSON integer 9223372036854775807 is too large or small for an Int32. Path '', line 1, position 19.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd")); ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: s. Path '', line 1, position 77.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("1E-06")); ExceptionAssert.Throws<JsonReaderException>("Input string '1E-06' is not a valid integer. Path '', line 1, position 5.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("1.1")); ExceptionAssert.Throws<JsonReaderException>("Input string '1.1' is not a valid integer. Path '', line 1, position 3.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("")); Assert.AreEqual(null, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("-")); ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid integer. Path '', line 1, position 1.", () => reader.ReadAsInt32()); }
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); }
public void ReadAsIntDecimal() { string json = @"{""Name"": 1.1}"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>( "Input string '1.1' is not a valid integer. Path 'Name', line 1, position 12.", () => { reader.ReadAsInt32(); }); }
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; }
public void ReadAsIntDecimal() { string json = @"{""Name"": 1.1}"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsInt32(); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(typeof(int), reader.ValueType); Assert.AreEqual(1, reader.Value); }
/// <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: break; } } return es; }
public void ReadOctalNumberAsInt32() { StringReader s = new StringReader(@"[0372, 0xFA, 0XFA]"); JsonTextReader jsonReader = new JsonTextReader(s); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.StartArray, jsonReader.TokenType); jsonReader.ReadAsInt32(); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(typeof(int), jsonReader.ValueType); Assert.AreEqual(250, jsonReader.Value); jsonReader.ReadAsInt32(); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(typeof(int), jsonReader.ValueType); Assert.AreEqual(250, jsonReader.Value); jsonReader.ReadAsInt32(); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(typeof(int), jsonReader.ValueType); Assert.AreEqual(250, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); }
/// <summary> /// Returns a List of EliteListing objects from a EDDB Json Array. /// JsonReader MUST currently point to the StartArray token for the Listing Array. /// </summary> /// <param name="jsonReader">JsonReader populated with the Listing Array</param> /// <returns>List of populated EliteListing Data</returns> private List<EliteListing> _ParseJsonListing(JsonTextReader jsonReader) { List<EliteListing> listings = new List<EliteListing>(); if (jsonReader.TokenType != JsonToken.StartArray) { AerDebug.LogError("_ParseJsonListing must be called at the start of an Array"); return null; } EliteListing currentListing = null; while (jsonReader.TokenType != JsonToken.EndArray) { jsonReader.Read(); switch (jsonReader.TokenType) { case JsonToken.StartObject: currentListing = new EliteListing(); break; case JsonToken.EndObject: listings.Add(currentListing); break; case JsonToken.PropertyName: switch (jsonReader.Value.ToString()) { case "id": currentListing.id = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "station_id": currentListing.StationId = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "commodity_id": currentListing.Commodity = GetCommodity(jsonReader.ReadAsInt32().GetValueOrDefault()); break; case "supply": currentListing.Supply = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "buy_price": currentListing.BuyPrice = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "sell_price": currentListing.SellPrice = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "demand": currentListing.Demand = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "collected_at": currentListing.UpdatedAt = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "update_count": currentListing.UpdateCount = jsonReader.ReadAsInt32().GetValueOrDefault(); break; default: AerDebug.LogError("Unknown JSON property name: " + jsonReader.Value.ToString()); break; } break; case JsonToken.EndArray: break; default: AerDebug.LogError("Unknown token type in listing list, " + jsonReader.TokenType); break; } } return listings; }
public void ReadInt32Overflow_Negative() { long i = int.MinValue; JsonTextReader reader = new JsonTextReader(new StringReader(i.ToString(CultureInfo.InvariantCulture))); reader.Read(); Assert.AreEqual(typeof(long), reader.ValueType); Assert.AreEqual(i, reader.Value); for (int j = 1; j < 1000; j++) { long total = -j + i; ExceptionAssert.Throws<OverflowException>( "Arithmetic operation resulted in an overflow.", () => { reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture))); reader.ReadAsInt32(); }); } }
public void CheckIntoEvent(string userId, string eventCode) { string json = ParamsToJSON ("user_id", userId, "event_code", eventCode); SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (CheckInUserPath), json); syrc.OnRestCallCompleted += (RestResult obj) => { ResponseBase ret = null; if (!obj.IsSuccess) { ret = new ResponseBase (obj.IsSuccess, obj.Result); } else { try { bool success = false; string msg = ""; using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result))) { while (jtr.Read()) { if (JsonKeyMatches (jtr, JsonToken.PropertyName, "Success")) { success = jtr.ReadAsInt32 () == 0; } } if (!success) { msg = "Unabled to parse JSON"; } ret = new ResponseBase (success, msg); } } catch (Exception e) { ret = new ResponseBase (false, GenerateParseErrorMessage (e)); } } SafeRaiseEvent (OnCheckIntoEventCompleted, ret); }; syrc.SendRestRequest (); }