public static void ThrowOnErrorResponse(this JsonValue jsonValue) { if (jsonValue.ContainsKey("error")) //pas error { throw new CDOException(jsonValue.Get("error"), jsonValue.Get("error_description")) { Scope = jsonValue.Get("scope") }; } if (jsonValue.ContainsKey("_errors")) //progress error { string code = ""; string message = jsonValue.Get("_retVal"); var errors = (JsonArray)jsonValue.Get("_errors"); foreach (var error in errors) { code = error.Get("_errorNum").ToString(); if (string.IsNullOrEmpty(message)) { message = error.Get("_errorMsg"); } break; } throw new CDOException(code, message); } }
static void Main(string[] args) { string jsonString = "{\"a\": 1,\"b\": \"z\",\"c\":[{\"Value\": 1}, {\"Value\": 2}]}"; JsonValue json = JsonValue.Parse(jsonString); // int test if (json.ContainsKey("a")) { int a = json["a"]; // type already set to int Console.WriteLine(a); } // string test if (json.ContainsKey("b")) { string b = json["b"]; // type already set to string Console.WriteLine(b); } // object array test if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array) { foreach (JsonValue j in json["c"]) { Console.WriteLine(j["Value"].ToString()); } } Console.WriteLine(); Console.Write("Press any key to exit."); Console.ReadKey(); }
public List <Election> ParseElectionJson(JsonValue data) { elections = new List <Election>(); if (!data.ContainsKey("error")) { JsonValue firstElection = data["election"]; elections.Add(new Election { id = firstElection["id"], name = firstElection["name"], date = firstElection["electionDay"] }); if (data.ContainsKey("otherElections")) { JsonArray upcomingElections = (JsonArray)data["otherElections"]; for (int i = 0; i < upcomingElections.Count; i++) { var current = upcomingElections[i]; elections.Add(new Election { id = current["id"], name = current["name"], date = current["electionDay"] }); } } } return(elections); }
private void _configureDialog(JsonValue json, JsonObject valuesJson) { if (json.ContainsKey(Constants.Grouped)) { Style = bool.Parse(json[Constants.Grouped].ToString()) ? UITableViewStyle.Grouped : UITableViewStyle.Plain; } if (json.ContainsKey(Constants.Title)) { Title = json[Constants.Title]; } if (json.ContainsKey(Constants.DataRoot)) { DataRootName = json[Constants.DataRoot]; } if (json.ContainsKey(Constants.RightBarItem)) { NavigationItem.RightBarButtonItem = _createButtonItemFor(Constants.RightBarItem, json, valuesJson); } if (json.ContainsKey(Constants.LeftBarItem)) { NavigationItem.LeftBarButtonItem = _createButtonItemFor(Constants.LeftBarItem, json, valuesJson); } }
public ListResponse(JsonValue json) { if (json != null) { BuildNumber = json["build"]; if (json.ContainsKey("torrentc")) { CacheID = json["torrentc"]; } if (json.ContainsKey("torrents")) { Torrents = ((JsonArray)json["torrents"]) .Select(j => new Torrent(j)) .ToDictionary(t => t.ID); } if (json.ContainsKey("torrentp")) { ChangedTorrents = ((JsonArray)json["torrentp"]) .Select(j => new Torrent(j)) .ToArray(); } if (json.ContainsKey("torrentm")) { RemovedTorrents = ((JsonArray)json["torrentm"]) .Select(j => new Torrent(j)) .ToArray(); } } }
private async Task <int> EventHandling(DataBaseWrapper db, JsonValue result) { if (result.ContainsKey("events")) { JsonArray arr = (JsonArray)result ["events"]; foreach (JsonValue v in arr) { var e = new Event() { type = v ["type"], msg = v ["msg"], nick = v ["nick"], text = v ["text"], time = v ["time"], author = v ["author"] }; db.Insert(e); } if (backgroundService != null) { await backgroundService.UpdateNotifications(); } } if (result.ContainsKey("onLoginError")) { return(1); } return(0); }
public static ResultForRoot FromJson(JsonValue json) { var result = new ResultForRoot( RootPosition.FromJson(json["position"]) ); foreach (Select select in SelectHelper.Values) { var selectStr = select.Stringify(); if (json.ContainsKey(selectStr)) { result.ResultsBySelect.Add(select, SelectResult.FromJson(json[selectStr])); } } if (json.ContainsKey("retractions")) { foreach (KeyValuePair <string, JsonValue> entry in json["retractions"]) { var entries = SegregatedEntries.FromJson(entry.Value); result.Retractions.Add(entry.Key, entries); } } return(result); }
public static JsonValue GetJsonValue <T>(this JsonValue json, Expression <Func <T> > expression) { if (json == null) { return(null); } MemberExpression body = (MemberExpression)expression.Body; string name = null; if (!GetNameFromAttribute(body.Member, ref name)) { name = GetJsonNamingConvention(body.Member.Name); } var result = json.ContainsKey(name) ? json[name] : null; if (result == null) { if (Debugger.IsAttached && !json.ContainsKey(name)) { throw new ArgumentOutOfRangeException("could not find jsonValue: " + name); } return(null); } if (result.JsonType == JsonType.Number || result.JsonType == JsonType.Boolean) { return(result.ToString()); } return(result); }
public CardSetFile ParseRawJsonFileLocation(string locationUrl) { if (string.IsNullOrEmpty(locationUrl)) { throw new ArgumentNullException("locationUrl"); } JsonValue jsonLocationUrl = null; try { jsonLocationUrl = JsonValue.Parse(locationUrl); } catch (ArgumentException ex) { _logger.LogError(ex, "Exception thrown in JsonParsingManager.ParseRawJsonFileLocation method."); throw new FormatException("locationUrl was not in JSON format.", ex); } CardSetFile cardSetFile = JsonConvert.DeserializeObject <CardSetFile>(locationUrl); string cdnRootKey = "cdn_root"; string dateKey = "expire_time"; string urlKey = "url"; if (!jsonLocationUrl.ContainsKey(cdnRootKey) || !jsonLocationUrl.ContainsKey(dateKey) || !jsonLocationUrl.ContainsKey(urlKey)) { FormatException ex = new FormatException("locationUrl was in JSON format, but did not have the correct keys."); _logger.LogError(ex, "Exception thrown in JsonParsingManager.ParseRawJsonFileLocation method."); throw ex; } return(cardSetFile); }
public JsonValue SendMessage(JsonValue message) { string origin; string destination; JsonValue json; if (message.ContainsKey("persist") && (message["persist"].Value is Boolean) && ((bool)message["persist"] == false)) { json = new JsonObject(); string type = "message"; if (message.ContainsKey("type")) { type = (string)message["type"].Value; } origin = (string)message["origin"].Value; destination = (string)message["destination"].Value; string content = null; if (message.ContainsKey("content")) { content = message["content"]; } json["type"] = type; json["origin"] = origin; json["destination"] = destination; json["content"] = content; json["persist"] = false; } else { lock (dbcon) { using (IDbTransaction transaction = dbcon.BeginTransaction()) { long id = SendMessage(dbcon, transaction, message); json = GetMessage(dbcon, transaction, id); transaction.Commit(); } } origin = (string)json["origin"]; destination = (string)json["destination"]; } // signal the created message to the watched users JsonValue messageJson = new JsonObject(); messageJson["event"] = "messagecreated"; messageJson["message"] = json; string jsonString = messageJson.ToString(); lock (instanceLock) { if (clients.ContainsKey(origin)) { clients[origin].Broadcast(jsonString); } if (clients.ContainsKey(destination)) { clients[destination].Broadcast(jsonString); } } RaisesMessageCreated(json); return(json); }
public void InvalidPropertyTest() { JsonValue target = AnyInstance.AnyJsonPrimitive; Assert.IsTrue(target.Count == 0); Assert.IsFalse(target.ContainsKey(string.Empty)); Assert.IsFalse(target.ContainsKey(AnyInstance.AnyString)); }
public static Entry FromJson(JsonValue json) { return(new Entry( json["count"], json.ContainsKey("first_game") ? Optional <GameHeader> .Create(GameHeader.FromJson(json["first_game"])) : Optional <GameHeader> .CreateEmpty(), json.ContainsKey("last_game") ? Optional <GameHeader> .Create(GameHeader.FromJson(json["last_game"])) : Optional <GameHeader> .CreateEmpty(), json.ContainsKey("elo_diff") ? Optional <long> .Create(json["elo_diff"]) : Optional <long> .CreateEmpty() )); }
public void PropertiesTest() { JsonValue target = AnyInstance.DefaultJsonValue; Assert.AreEqual(JsonType.Default, target.JsonType); Assert.AreEqual(0, target.Count); Assert.AreEqual(false, target.ContainsKey("hello")); Assert.AreEqual(false, target.ContainsKey(string.Empty)); }
void IClassifyObjectProcessor <JsonValue> .AfterSerialize(JsonValue element) { if (element is JsonDict && element.ContainsKey("Published") && element["Published"].GetStringSafe()?.EndsWith("Z") == true) { element["Published"] = element["Published"].GetString().Apply(s => s.Remove(s.Length - 1)); } if (Type != KtaneModuleType.Regular && element is JsonDict && element.ContainsKey("Souvenir")) { element.Remove("Souvenir"); } }
/// <summary><para>Recursive funhouse of applying rules different ways depending on how they are described. /// This figures out how a rule should be applied. Rules are described in data as <paramref name="thing"/>. </para> /// <para>Applying an array causes every element of the array to be applied.</para> /// <para>Applying an object causes a 'key' of the object to be selected using WeightedChoose, then the key is applied.</para> /// <para>Applying a string causes us to search for the next rule named by the string, in the current <paramref name="rule"/>, /// or if it can't be found there, in the <see cref="ruleset"/>. </para> /// <para>Regardless of what is selected, the change in rules is recorded in the <see cref="State.genHistory"/></para></summary> /// <param name="state"> Current generator state </param> /// <param name="thing"> The thing we are trying to apply </param> /// <param name="rule"> The rule we are currently in (so we can find nested rules) </param> private void Apply(State state, JsonValue thing, JsonObject rule) { string path = state.lastHistory["path"].stringVal; // Rules eventually are told to us by strings describing them. if (thing.isString) { Console.WriteLine($"Applying String rule at {path} => {thing.stringVal}"); var nextRule = FindRule(rule, thing.stringVal); if (nextRule is JsonObject) { ApplyRule(state, nextRule as JsonObject, state.lastHistory); } } // May have arrays to describe a sequence of rules to apply if (thing.isArray) { Console.WriteLine($"Applying Array rule at {path} => {thing.ToString()}"); foreach (var val in (thing as JsonArray)) { if (val.isString) { // If we're at a string, add it then apply it, since the next Apply will invoke a rule. state.PushHistory(val.stringVal); } Apply(state, val, rule); if (val.isString) { state.PopHistory(); } } } // If we're in an object, we need to make a decision of what name to apply, // as well as other things. if (thing.isObject) { if (thing.ContainsKey("repeat") && thing.ContainsKey("rule")) { // Meta Object: Contains instruction to repeat something multiple times... RepeatedApply(state, thing, rule, path); // todo later: support other meta-applications with objects describing them... } else { string chosen = state.WeightedChoose(thing as JsonObject); Console.WriteLine($"Applying Weighted Choice rule at {path} => {chosen}"); state.PushHistory(chosen); Apply(state, chosen, rule); state.PopHistory(); } } }
public void SimpleContactJsonString(string firstName, string lastName, string email, string username, string department, string accountID) { string json = Contact.Create(firstName, lastName, email, username, department, accountID).ToString(); JsonValue recover = JsonValue.Parse(json); Assert.Equal(6, recover.Count); Assert.True(recover.ContainsKey("firstname")); Assert.True(recover.ContainsKey("lastname")); Assert.True(recover.ContainsKey("emailaddress1")); Assert.True(recover.ContainsKey("new_username")); Assert.Equal($"/accounts({testGuid})", recover["*****@*****.**"]); }
public string ParseElectionInfoJson(JsonValue data) { string response = ""; if (data.ContainsKey("election")) { JsonValue election = data["election"]; response = response + election["name"] + "\n" + election["electionDay"] + "\n"; } if (data.ContainsKey("pollingLocations")) { JsonArray pollingLocations = (JsonArray)data["pollingLocations"]; for (int i = 0; i < pollingLocations.Count; i++) { JsonValue current = pollingLocations[i]; JsonValue address = current["address"]; response = address.ContainsKey("locationName") ? response + address["locationName"] + "\n" : response; response = address.ContainsKey("line1") ? response + address["line1"] : response; response = address.ContainsKey("line2") ? response + "\n" + address["line2"] : response; response = address.ContainsKey("line3") ? response + "\n" + address["line3"] : response; response = address.ContainsKey("city") ? response + "\n" + address["city"] : response; response = address.ContainsKey("state") ? response + " " + address["state"] : response; response = address.ContainsKey("zip") ? response + ", " + address["zip"] + "\n" : response; response = current.ContainsKey("notes") ? response + current["notes"] + "\n": response; response = current.ContainsKey("pollingHours") ? response + "Polling Hours:\n" + current["pollingHours"] + "\n\n" : response; } } if (data.ContainsKey("contests")) { JsonArray contests = (JsonArray)data["contests"]; for (int i = 0; i < contests.Count; i++) { JsonValue current = contests[i]; response = current.ContainsKey("office") ? response + "Contested Positions\n\n" + current["office"] + "\n\n" : response; if (current.ContainsKey("candidates")) { response = response + "candidates\n\n"; JsonArray candidates = (JsonArray)current["candidates"]; for (int i2 = 0; i2 < candidates.Count; i2++) { JsonValue currentCand = candidates[i2]; response = currentCand.ContainsKey("name") ? response + currentCand["name"] + "\n" : response; response = currentCand.ContainsKey("party") ? response + currentCand["party"] + "\n" : response; response = currentCand.ContainsKey("phone") ? response + "phone #: " + currentCand["phone"] + "\n" : response; response = currentCand.ContainsKey("email") ? response + currentCand["email"] + "\n\n" : response; } } } } return(response); }
public static RootPosition FromJson(JsonValue json) { return(new RootPosition( json["fen"], json.ContainsKey("move") ? Optional <string> .Create(json["move"]) : Optional <string> .CreateEmpty() )); }
internal Parser(JsonValue json) { _sourceparser = json; MissingTokens = json.ContainsKey("missing_tokens") ? new HashSet <string>(json["missing_tokens"].Select(x => (string)x)) : new HashSet <string>(); }
public static async Task <List <ListItem> > GetListItems(string listName, string select, string expand, int top, string filter, string orderBy) { List <ListItem> listItems = new List <ListItem>(); try { string requestUrl = string.Format("{0}/GetByTitle('{1}')/Items", Url, listName); if (!string.IsNullOrEmpty(select)) { requestUrl += string.Format("?$select={0}", select); } if (!string.IsNullOrEmpty(expand)) { requestUrl += string.Format("&$expand={0}", expand); } if (top > 0) { requestUrl += string.Format("&$top={0}", top); } if (!string.IsNullOrEmpty(filter)) { requestUrl += string.Format("&$filter={0}", filter.Replace(" ", "%20")); } if (!string.IsNullOrEmpty(orderBy)) { requestUrl += string.Format("&$orderby={0}", orderBy.Replace(" ", "%20")); } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); request.Method = "GET"; request.Accept = "application/json; odata=verbose"; request.Headers.Add("Authorization", "Bearer " + App.Token); using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { using (StreamReader stream = new StreamReader(response.GetResponseStream())) { string content = await stream.ReadToEndAsync(); JsonValue jsonValue = JsonValue.Parse(content); if (jsonValue.ContainsKey("d") && jsonValue["d"].ContainsKey("results")) { for (int i = 0; i < jsonValue["d"]["results"].Count; i++) { listItems.Add(new ListItem(jsonValue["d"]["results"][i])); } } } } } } catch (Exception) { listItems = new List <ListItem>(); } return(listItems); }
public RemoteLocationManager(string name, string className, string path, ulong internalId, ulong parentInternalId, JsonValue objectDef) : base(name, className, path, internalId, parentInternalId) { if (!objectDef.ContainsKey("mismatches")) { return; } var mismatches = objectDef["mismatches"]; mMismatches = new LocationMismatch[mismatches.Count]; int index = 0; foreach (JsonValue item in mismatches) { var remoteDecoder = (RemoteDecoder)RemoteObjectManager.LoadObject(item["decoder"]); var reason = item["reason"]; String mappedLocation = item.ContainsKey("location") ? item["location"] : null; var mismatch = new LocationMismatch(remoteDecoder, reason, mappedLocation); mMismatches[index++] = mismatch; } }
public RemoteLocation(string name, string className, string path, ulong internalId, ulong parentInternalId, JsonValue data) : base(name, className, path, internalId, parentInternalId) { mBeginAddress = data["begin"]; mEndAddress = data["end"]; if (!data.ContainsKey("decoders")) { return; } var decoders = data["decoders"]; var count = decoders.Count; mRemoteDecoders = new RemoteDecoder[count]; for (int i = 0; i < count; ++i) { var decInfo = decoders[i]; if (decInfo == null) { continue; } var remoteObject = RemoteObjectManager.LoadObject(decInfo); mRemoteDecoders[i] = remoteObject as RemoteDecoder; } }
private static string getSessionName(string filePath, int sessionId) { Result information = getImporterInformation(filePath); if (information.success == false) { // This shouldn't happen, other getImporterInformation is used in different ways. LogB.Information("chronojumpImporter::getSessionName failed. Output:" + information.output + "Error:" + information.error); return("UNKNOWN"); } else { JsonValue json = JsonValue.Parse(information.output); if (!json.ContainsKey("sessions")) { LogB.Information("Trying to import a session but sessions doesn't exist. Output:" + information.output); return("UNKNOWN"); } foreach (JsonValue session in json["sessions"]) { if (session.ContainsKey("uniqueID") && session ["uniqueID"] == sessionId) { return(JsonUtils.valueOrDefault(session, "name", "UNKNOWN")); } } LogB.Information("Trying to import a session that we can't find the name. Output:" + information.output); return("UNKNOWN"); } }
static string GetString (JsonValue obj, string key) { if (obj.ContainsKey (key)) if (obj [key].JsonType == JsonType.String) return (string) obj [key]; return null; }
public static Offer FromJson(JsonValue item) { if (item != null && item.ContainsKey("id")) { Offer offer = new Offer(); var json = item; offer.Id = json.GetJsonValue(() => offer.Id); offer.SelectStores = json.GetJsonValue(() => offer.SelectStores); offer.Promoted = json.GetJsonValue(() => offer.Promoted); offer.Heading = json.GetJsonValue(() => offer.Heading); offer.Description = json.GetJsonValue(() => offer.Description); offer.Price = json.GetJsonValue(() => offer.Price); offer.Preprice = json.GetJsonValue(() => offer.Preprice); offer.Images = Images.FromJson(json); offer.Url = json.GetJsonValue(() => offer.Url); offer.RunFrom = json.GetJsonValue(() => offer.RunFrom); offer.RunTill = json.GetJsonValue(() => offer.RunTill); offer.Dealer = Dealer.FromJson(json); //offer.Timespan = Timespan.FromJson(json.GetJsonValue(() => offer.Timespan)); offer.Catalog = CatalogIndex.FromJson(json); offer.Store = Store.FromJson(json); return(offer); } return(null); }
public static bool ScanState(DirectoryInfo rootPath, string stateFileName, out string encryptKey) { FileInfo fi = new FileInfo(Path.Combine(rootPath.FullName, stateFileName)); if (!fi.Exists) { encryptKey = null; return(false); } using (StreamReader sr = fi.OpenText()) { string json = sr.ReadToEnd(); JsonValue state = JsonValue.Parse(json); if (!state.ContainsKey("os_crypt")) { encryptKey = null; return(false); } JsonValue osCrypt = state["os_crypt"]; if (!osCrypt.ContainsKey("encrypted_key")) { encryptKey = null; return(false); } encryptKey = osCrypt["encrypted_key"]; return(true); } }
/// <summary> /// /// </summary> /// <param name="capabilitiesResult"></param> /// <returns></returns> public static StationsData ExtractStationData(string capabilitiesResult) { JsonValue values = JsonValue.Parse(capabilitiesResult); StationsData stationsData = new StationsData(); if (values.ContainsKey("contents")) { var contents = values["contents"]; for (int i = 0; i < contents.Count; i++) { var entry = contents[i]; var identifier = entry["identifier"].ToString().Trim(new char[] { '"' }); var property = identifier.Split('.')[0]; var station = identifier.Split('@')[1]; if (stationsData.HasStation(station)) { stationsData.AddCapabilityToExistingStation(station, property); } else { if (entry.ContainsKey("observedArea")) { var location = entry["observedArea"]["lowerLeft"]; var longitude = location[1]; var latitude = location[0]; stationsData.AddNewStation(station, latitude, longitude, property); } } } } Console.WriteLine(stationsData); return(stationsData); }
/// <summary> /// Get timestamp_ms field or pseudo timestamp string. /// </summary> /// <param name="graph">json object graph</param> /// <returns>timestamp code(millisecond)</returns> internal static string GetTimestamp(JsonValue graph) { return(graph.ContainsKey("timestamp_ms") ? graph["timestamp_ms"].AsString() : ((long)(DateTime.Now.ToUniversalTime() - StreamMessage.SerialTimeStandard) .TotalMilliseconds).ToString()); }
internal static void OnAuthResponse(IAsyncResult rs) { NetworkRequest networkRequest = rs.AsyncState as NetworkRequest; NetworkResponse networkResponse = networkRequest.EndGetResponse(rs); NetworkStreamReader streamReader = networkResponse.GetStreamReader(); string text = streamReader.ReadToEnd(); if (text.Length > 0) { JsonValue jsonValue = JsonValue.Parse(text); if (jsonValue.ContainsKey("b")) { Network.serverTicket = (string)jsonValue.GetValue("b").GetValue("w"); Network.serverStatus = NetworkState.NetworkServerReady; } else { Network.serverStatus = NetworkState.NetworkServerFailed; } } else { Network.serverStatus = NetworkState.NetworkServerFailed; } }
public async Task <bool> TryToLogin(string username, string password) { // Create an HTTP web request using the URL: string url = "http://tojejedno.scrilab.sk/mina/SharePoint/api/login.php?username="******"&password="******"application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream)); if (jsonDoc.ContainsKey("result")) { string res = jsonDoc["result"]; if (res.Equals("OK")) { return(true); } } return(false); // Return the JSON document: } return(false); } return(false); }
public void IDictionary() { JsonValue test = new JsonValue() { {"one", 1}, {"two", 2}, {"three", 3} }; Assert.That((int)test["one"], Is.EqualTo(1)); test["one"] = 5; Assert.That((int)test["one"], Is.EqualTo(5)); test["one"] = 1; var keys = test.Keys; Assert.That(keys.Count, Is.EqualTo(3)); Assert.That(keys.Contains("one"), Is.True); Assert.That(keys.Contains("two"), Is.True); Assert.That(keys.Contains("three"), Is.True); var values = test.Values; Assert.That(values.Count, Is.EqualTo(3)); var intvalues = values.Select(x => (int)x).ToArray(); Array.Sort(intvalues); for (int i = 0; i < 3; i++) { Assert.That(intvalues[i], Is.EqualTo(i + 1)); } test.Add("four", 4); Assert.That(test.Count, Is.EqualTo(4)); Assert.That((int)test["four"], Is.EqualTo(4)); JsonValue val; Assert.That(test.TryGetValue("one", out val), Is.True); Assert.That((int)val, Is.EqualTo(1)); Assert.That(test.TryGetValue("seven", out val), Is.False); Assert.That(val, Is.Null); Assert.That(test.ContainsKey("four"), Is.True); test.Remove("four"); Assert.That(test.Count, Is.EqualTo(3)); Assert.That(test.ContainsKey("four"), Is.False); }
public void DictionaryLiteral() { JsonValue test = new JsonValue() { {"three", 3}, {"two", 2}, {"one", 1}, {"blast", "off!"} }; Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.ContainsKey("three"), Is.True); Assert.That(test.ContainsKey("two"), Is.True); Assert.That(test.ContainsKey("one"), Is.True); Assert.That(test.ContainsKey("blast"), Is.True); Assert.That(test["three"].Type, Is.EqualTo(JsonType.Int)); Assert.That(test["two"].Type, Is.EqualTo(JsonType.Int)); Assert.That(test["one"].Type, Is.EqualTo(JsonType.Int)); Assert.That(test["blast"].Type, Is.EqualTo(JsonType.String)); Assert.That((int)test["three"], Is.EqualTo(3)); Assert.That((int)test["two"], Is.EqualTo(2)); Assert.That((int)test["one"], Is.EqualTo(1)); Assert.That((string)test["blast"], Is.EqualTo("off!")); }
/// <summary> /// Get timestamp_ms field or pseudo timestamp string. /// </summary> /// <param name="graph">json object graph</param> /// <returns>timestamp code(millisec)</returns> internal static string GetTimestamp(JsonValue graph) { return graph.ContainsKey("timestamp_ms") ? graph["timestamp_ms"].AsString() : ((long)(DateTime.Now.ToUniversalTime() - StreamMessage.SerialTime) .TotalMilliseconds).ToString(); }
/// <summary> /// Check parse streamed JSON line as normal (not direct-message) status /// </summary> /// <param name="graph">JSON object graph</param> /// <param name="handler">stream handler</param> /// <returns></returns> internal static bool ParseStreamLineAsStatus(JsonValue graph, IStreamHandler handler) { if (!graph.ContainsKey("text")) return false; handler.OnStatus(new TwitterStatus(graph)); return true; }
public void KVPCollection() { JsonValue test = new JsonValue() { {"one", 1}, {"two", 2}, {"three", 3}, }; test.Remove(new KeyValuePair<string, JsonValue>("one", 1)); Assert.That(test.Count, Is.EqualTo(2)); Assert.Throws<KeyNotFoundException>(() => test["one"].ToString()); KeyValuePair<string, JsonValue>[] dest = new KeyValuePair<string, JsonValue>[2]; test.CopyTo(dest, 0); for (int i = 0; i < 2; ++i) { Assert.That(test[dest[i].Key].Equals(dest[i].Value)); } Assert.That(test.Contains(new KeyValuePair<string, JsonValue>("two", 2))); test.Add(new KeyValuePair<string, JsonValue>("four", 4)); Assert.That(test.ContainsKey("four"), Is.True); Assert.That((int)test["four"], Is.EqualTo(4)); }
internal TwitterStatus(JsonValue json) { // read numeric id and timestamp Id = json["id_str"].AsString().ParseLong(); CreatedAt = json["created_at"].AsString().ParseDateTime(ParsingExtension.TwitterDateTimeFormat); // check extended_tweet is existed var exjson = json.ContainsKey("extended_tweet") ? json["extended_tweet"] : json; // read full_text ?? text var text = exjson.ContainsKey("full_text") ? exjson["full_text"] : exjson["text"]; Text = ParsingExtension.ResolveEntity(text.AsString()); var array = exjson["display_text_range"].AsArrayOrNull()?.AsLongArray(); if (array != null && array.Length >= 2) { DisplayTextRange = new Tuple<int, int>((int)array[0], (int)array[1]); } if (exjson.ContainsKey("extended_entities")) { // get correctly typed entities array var orgEntities = TwitterEntity.ParseEntities(json["entities"]).ToArray(); var extEntities = TwitterEntity.ParseEntities(json["extended_entities"]).ToArray(); // merge entities Entities = orgEntities.Where(e => !(e is MediaEntity)) .Concat(extEntities) // extended entities contains media entities only. .ToArray(); } else if (exjson.ContainsKey("entities")) { Entities = TwitterEntity.ParseEntities(exjson["entities"]).ToArray(); } else { Entities = new TwitterEntity[0]; } if (json.ContainsKey("recipient")) { // THIS IS DIRECT MESSAGE! StatusType = StatusType.DirectMessage; User = new TwitterUser(json["sender"]); Recipient = new TwitterUser(json["recipient"]); } else { StatusType = StatusType.Tweet; User = new TwitterUser(json["user"]); Source = json["source"].AsString(); InReplyToStatusId = json["in_reply_to_status_id_str"].AsString().ParseNullableId(); InReplyToUserId = json["in_reply_to_user_id_str"].AsString().ParseNullableId(); InReplyToScreenName = json["in_reply_to_screen_name"].AsString(); if (json.ContainsKey("retweeted_status")) { var retweeted = new TwitterStatus(json["retweeted_status"]); RetweetedStatus = retweeted; RetweetedStatusId = retweeted.Id; // merge text and entities Text = retweeted.Text; Entities = retweeted.Entities; } if (json.ContainsKey("quoted_status")) { var quoted = new TwitterStatus(json["quoted_status"]); QuotedStatus = quoted; QuotedStatusId = quoted.Id; } var coordinates = json["coordinates"].AsArrayOrNull()?.AsDoubleArray(); if (coordinates != null) { Longitude = coordinates[0]; Latitude = coordinates[1]; } } }