public void ProcessMessage(string message) { Console.WriteLine("incoming: " + message); JsonReader jsonReader = new JsonTextReader(new StringReader(message)); string messageHeader = ""; while (jsonReader.Read()) { if ((jsonReader.TokenType == JsonToken.PropertyName) && (jsonReader.Value.ToString() == "Request")) { jsonReader.Read(); messageHeader = jsonReader.Value.ToString(); break; } } if (messageHeader.Length > 0) { BaseProcessor processor = GetProcessor(messageHeader); if (processor != null) { Type messageType = GetMessageType(messageHeader); if (messageType != null) { processor.Process((BaseMessage) JsonConvert.DeserializeObject(message, messageType)); } } } }
public void ReadJsonWithInnerObjectTest() { const string json = "{\"properties\":{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}"; AttributesTableConverter target = new AttributesTableConverter(); using (JsonTextReader reader = new JsonTextReader(new StringReader(json))) { JsonSerializer serializer = new JsonSerializer(); // read start object token and prepare the next token reader.Read(); reader.Read(); AttributesTable result = (AttributesTable) target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer); Assert.IsFalse(reader.Read()); // read the end of object and ensure there are no more tokens available Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); Assert.AreEqual("value1", result["test1"]); Assert.IsNotNull(result["test2"]); Assert.IsInstanceOf<IAttributesTable>(result["test2"]); IAttributesTable inner = (IAttributesTable)result["test2"]; Assert.AreEqual(1, inner.Count); Assert.AreEqual("innervalue1", inner["innertest1"]); } }
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); }
protected override object DeserializeObject(ArraySegment <byte> value) { using (var ms = new MemoryStream(value.Array, value.Offset, value.Count, writable: false)) using (var tr = new StreamReader(ms)) using (var jr = new Newtonsoft.Json.JsonTextReader(tr)) { jr.Read(); if (jr.TokenType == JsonToken.StartArray) { // read type var typeName = jr.ReadAsString(); var type = readCache.GetOrAdd(typeName, x => Type.GetType(x, throwOnError: true)); // Get type or Register type // read object jr.Read(); var deserializedValue = jsonSerializer.Deserialize(jr, type); return(deserializedValue); } else { throw new InvalidDataException("JsonTranscoder only supports [\"TypeName\", object]"); } } }
private string SelectOperationInternal(Message message) { byte[] rawBody; using (XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents()) { bodyReader.ReadStartElement("Binary"); rawBody = bodyReader.ReadContentAsBase64(); } string operation = null; using (var bodyReader = new JsonTextReader(new StreamReader(new MemoryStream(rawBody)))) { while (bodyReader.Read()) { if (bodyReader.TokenType == JsonToken.PropertyName) { string propertyName = (string)bodyReader.Value; if (propertyName.Equals("method", StringComparison.Ordinal)) { if (!bodyReader.Read() || bodyReader.TokenType != JsonToken.String) throw new InvalidOperationException("Invalid message format."); operation = (string)bodyReader.Value; break; } } } } return operation; }
public override void Deserialize(Node node, string data) { TextReader tr = new StringReader(data); Dictionary<string, object> properties = new Dictionary<string, object>(); using(JsonTextReader jsonReader = new JsonTextReader(tr)) { while (jsonReader.Read()){ if (jsonReader.TokenType == JsonToken.PropertyName) { string name = jsonReader.Value.ToString(); if (jsonReader.Read()) { switch (jsonReader.TokenType) { case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Integer: properties.Add(name, jsonReader.Value); break; case JsonToken.StartArray: List<object> objs = new List<object>(); while(jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { objs.Add(jsonReader.Value); } properties.Add(name, objs.ToArray()); break; } } } } } UpdateNode (node, properties); }
public void ReadBigInteger() { string json = @"{ ParentId: 1, 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); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonTextReader.TokenType); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonTextReader.TokenType); Assert.AreEqual(typeof(BigInteger), jsonTextReader.ValueType); Assert.AreEqual(BigInteger.Parse("333333333333333333333333333333333333333"), jsonTextReader.Value); Assert.IsTrue(jsonTextReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType); Assert.IsFalse(jsonTextReader.Read()); JObject o = JObject.Parse(json); var i = (BigInteger)((JValue)o["ChildId"]).Value; Assert.AreEqual(BigInteger.Parse("333333333333333333333333333333333333333"), i); }
public static DateTimeOffset? ParseDateTimeOffset(JToken value) { var jValue = value as JValue; if (jValue != null) { if (jValue.Value == null) return null; if (jValue.Value is DateTimeOffset) return jValue.Value<DateTimeOffset>(); } var rawValue = value.AsString(); if (string.IsNullOrWhiteSpace(rawValue)) return null; rawValue = rawValue.Replace("NeoDate", "Date"); if (!DateRegex.IsMatch(rawValue)) { DateTimeOffset parsed; if (!DateTimeOffset.TryParse(rawValue, out parsed)) return null; } var text = string.Format("{{\"a\":\"{0}\"}}", rawValue); var reader = new JsonTextReader(new StringReader(text)) {DateParseHandling = DateParseHandling.DateTimeOffset}; reader.Read(); // JsonToken.StartObject reader.Read(); // JsonToken.PropertyName return reader.ReadAsDateTimeOffset(); }
private void ReadInitialHit(JsonTextReader jsonReader) { // advance to StartObject while (jsonReader.Read() && jsonReader.TokenType != JsonToken.StartObject) ; List<object> initialValues = new List<object>(); // read initial hit until EndObject inSource = false; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndObject) { if (jsonReader.TokenType == JsonToken.PropertyName) { if (!inSource && string.CompareOrdinal((string)jsonReader.Value, "_source") == 0) { jsonReader.Read(); jsonReader.Read(); inSource = true; } _fieldNames.Add((string)jsonReader.Value); jsonReader.Read(); // read value _fieldTypes.Add(jsonReader.ValueType); initialValues.Add(jsonReader.Value); } } currentHit = initialValues.ToArray(); }
private async Task ParseStepsAsync( Stream stream, RecipeDescriptor descriptor, Func<RecipeDescriptor, RecipeStepDescriptor, Task> stepActionAsync) { var serializer = new JsonSerializer(); StreamReader streamReader = new StreamReader(stream); JsonTextReader reader = new JsonTextReader(streamReader); // Go to Steps, then iterate. while (reader.Read()) { if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray) { int stepId = 0; while (reader.Read() && reader.Depth > 1) { if (reader.Depth == 2) { var child = JToken.Load(reader); await stepActionAsync(descriptor, new RecipeStepDescriptor { Id = (stepId++).ToString(CultureInfo.InvariantCulture), RecipeName = descriptor.Name, Name = child.Value<string>("name"), Step = child }); } } } } }
public static string ParseCheckpointTagCorrelationId(this string source) { try { if (string.IsNullOrEmpty(source)) return null; var reader = new JsonTextReader(new StringReader(source)); if (!reader.Read()) return null; if (reader.TokenType != JsonToken.StartObject) return null; while (true) { CheckpointTag.Check(reader.Read(), reader); if (reader.TokenType == JsonToken.EndObject) break; if (reader.TokenType != JsonToken.PropertyName) return null; var name = (string) reader.Value; switch (name) { default: if (!reader.Read()) return null; var jToken = JToken.ReadFrom(reader); if (name == "$correlationId") return jToken.ToString(); break; } } return null; } catch (JsonReaderException) { return null; } }
public static SystemSettings FromJsonBytes(byte[] json) { using (var reader = new JsonTextReader(new StreamReader(new MemoryStream(json)))) { Check(reader.Read(), reader); Check(JsonToken.StartObject, reader); StreamAcl userStreamAcl = null; StreamAcl systemStreamAcl = null; while (true) { Check(reader.Read(), reader); if (reader.TokenType == JsonToken.EndObject) break; Check(JsonToken.PropertyName, reader); var name = (string)reader.Value; switch (name) { case SystemMetadata.UserStreamAcl: userStreamAcl = StreamMetadata.ReadAcl(reader); break; case SystemMetadata.SystemStreamAcl: systemStreamAcl = StreamMetadata.ReadAcl(reader); break; default: { Check(reader.Read(), reader); // skip JToken.ReadFrom(reader); break; } } } return new SystemSettings(userStreamAcl, systemStreamAcl); } }
public void DeserializeRequest(Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] rawBody = bodyReader.ReadContentAsBase64(); MemoryStream ms = new MemoryStream(rawBody); StreamReader sr = new StreamReader(ms); JsonSerializer serializer = new JsonSerializer { PreserveReferencesHandling = PreserveReferencesHandling.Objects }; if (parameters.Length == 1) { // single parameter, assuming bare parameters[0] = serializer.Deserialize(sr, this.operation.Messages[0].Body.Parts[0].Type); } else { // multiple parameter, needs to be wrapped JsonReader reader = new JsonTextReader(sr); reader.Read(); if (reader.TokenType != JsonToken.StartObject) { throw new InvalidOperationException("Input needs to be wrapped in an object"); } reader.Read(); while (reader.TokenType == JsonToken.PropertyName) { string parameterName = reader.Value as string; reader.Read(); if (this.parameterNames.ContainsKey(parameterName)) { int parameterIndex = this.parameterNames[parameterName]; parameters[parameterIndex] = serializer.Deserialize(reader, this.operation.Messages[0].Body.Parts[parameterIndex].Type); } else { reader.Skip(); } reader.Read(); } reader.Close(); } sr.Close(); ms.Close(); }
public void DeserializeRequest(Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } var bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); var rawBody = bodyReader.ReadContentAsBase64(); var ms = new MemoryStream(rawBody); var sr = new StreamReader(ms); var serializer = CreateJsonSerializer(); // new JsonSerializer(); if (parameters.Length == 1) { // single parameter, assuming bare parameters[0] = serializer.Deserialize(sr, _operation.Messages[0].Body.Parts[0].Type); } else { // multiple parameter, needs to be wrapped JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr); reader.Read(); if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject) { throw new InvalidOperationException("Input needs to be wrapped in an object"); } reader.Read(); while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { var parameterName = reader.Value as string; reader.Read(); if (_parameterNames.ContainsKey(parameterName)) { var parameterIndex = _parameterNames[parameterName]; parameters[parameterIndex] = serializer.Deserialize(reader, _operation.Messages[0].Body.Parts[parameterIndex].Type); } else { reader.Skip(); } reader.Read(); } reader.Close(); } sr.Close(); ms.Close(); }
static void Main(string[] args) { String ini; if (args.Length < 1) { Console.WriteLine("Please enter the name of the ini file"); ini = Console.ReadLine(); } else ini = args[0]; Console.WriteLine(ini); var twit = new Twitter(ini); //twit.testStream(); var testCount = 100; twit.populateData(testCount); while (twit.Data.Count() < testCount - 1) { Console.WriteLine(twit.Data.Count()); System.Threading.Thread.Sleep(5000); } twit.writeDateToFile(@"C:\Users\Kevin\Documents\TestJson\data.txt"); //twit.testStream("Disney"); Tweets data = new Tweets(); JsonSerializer serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; using (StreamReader sr = new StreamReader(@"C:\Users\Kevin\Documents\TestJson\data.txt")) using (JsonTextReader jr = new JsonTextReader(sr)) { if(!jr.Read() || jr.TokenType != JsonToken.StartArray) { throw new Exception("Expected start of array"); } while (jr.Read()) { if (jr.TokenType == JsonToken.EndArray) break; var item = serializer.Deserialize<TweetData>(jr); data.add(item); } } Console.WriteLine("done"); foreach (var tweet in data) { Console.WriteLine(tweet.text); } //twit.getData(); //while (twit.Data.Length <= 1) ; //Console.WriteLine(twit.Data+"\n"); //Twitter.testStream(ini); var news = new News(); news.getGoogleNews("Disney"); foreach (var article in news.Data) { Console.WriteLine(article.Title+" "+article.publishData.ToString() ); } Console.WriteLine("Done with everything"); Console.ReadLine(); }
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); }
private void ReadJsonFile(object s, DoWorkEventArgs args) { BackgroundWorker worker = s as BackgroundWorker; bool exit = false; string road = string.Format("Resources/JsonRoads/{0}.json", Configuration.FAKE_JSON_ROAD); using (Stream stream = Application.GetResourceStream(new Uri(road, UriKind.Relative)).Stream) { using (TextReader textReader = new StreamReader(stream)) { using (var jsonReader = new JsonTextReader(textReader)) { while (jsonReader.Read() && !exit) { FakeGeoCoordinateObject loc = new FakeGeoCoordinateObject(); loc.Course = double.NaN; if (jsonReader.TokenType == JsonToken.StartObject) { do { if (worker.CancellationPending == true) { args.Cancel = true; exit = true; } if (jsonReader.TokenType == JsonToken.PropertyName && jsonReader.Value.Equals("lat")) { jsonReader.Read(); loc.Latitude = Convert.ToDouble(jsonReader.Value); } else if (jsonReader.TokenType == JsonToken.PropertyName && jsonReader.Value.Equals("lng")) { jsonReader.Read(); loc.Longitude = Convert.ToDouble(jsonReader.Value); } else if (jsonReader.TokenType == JsonToken.PropertyName && jsonReader.Value.Equals("bearing")) { jsonReader.Read(); loc.Course = Convert.ToDouble(jsonReader.Value); } } while (jsonReader.TokenType != JsonToken.EndObject && jsonReader.Read() && !exit); if (!exit) { this.events.Push(loc); Thread.Sleep(Configuration.FAKE_LOCATION_DELAY); } } } } } } }
public void ParsingQuotedPropertyWithControlCharacters() { JsonReader reader = new JsonTextReader(new StringReader(@"{'hi\r\nbye':1}")); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual("hi\r\nbye", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(1L, reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); }
public static bool GeoEnabled() { bool result = false; string url = "https://api.twitter.com/1.1/account/verify_credentials.json"; Dictionary<string, string> headers = TwitterOAuth.getInstance().createOAuthHeader("GET", url, new Dictionary<string, string>()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ServicePoint.Expect100Continue = false; foreach (string key in headers.Keys) { request.Headers.Add(key, headers[key]); } request.Method = WebRequestMethods.Http.Get; request.Timeout = 8000; if (Properties.Settings.Default.ProxyServer.Length > 0) { request.Proxy = new WebProxy(string.Format("http://{0}:{1}", Properties.Settings.Default.ProxyServer, Properties.Settings.Default.ProxyPort)); } using (WebResponse response = request.GetResponse()) using (JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream()))) { /* string r = reader.ReadToEnd(); XmlDocument doc = new XmlDocument(); doc.LoadXml(r); XmlNodeList list = doc.SelectNodes("/user/geo_enabled"); if (list != null && list.Count > 0) { XmlNode node = list[0]; result = bool.Parse(node.InnerText); } */ while (reader.Read()) { if (reader.Value != null) { if (reader.TokenType == JsonToken.PropertyName && reader.Value.ToString() == "geo_enabled") { reader.Read(); result = (Boolean)reader.Value; } } } } return result; }
private static List<Redirect> ReadRedirects() { if (RedirectHandler.Redirects == null) { var path = WebConfigurationManager.AppSettings["redirects"] ?? "~/App_Data/redirects.json"; path = Container.Current.Resolve<IServerUtility>().MapPath(path); var redirects = new List<Redirect>(); using (var file = File.OpenText(path)) using (var reader = new JsonTextReader(file)) { string from = null; while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { from = ((string)reader.Value).ToLowerInvariant(); } else if (reader.TokenType == JsonToken.String) { redirects.Add(new Redirect() { From = from, To = ((string)reader.Value).ToLowerInvariant() }); } } } RedirectHandler.Redirects = redirects; } return RedirectHandler.Redirects; }
public static IEnumerable<RustcMessageJson> Parse(String output) { var reader = new JsonTextReader(new StringReader(output)) {SupportMultipleContent = true}; while (reader.Read()) yield return serializer.Deserialize<RustcMessageJson>(reader); }
public static void LoadGame(string filename) { char separator = Path.DirectorySeparatorChar; string path = "SavedGames" + separator + PlayerManager.GetPlayerName() + separator + filename + ".json"; if(!File.Exists(path)) { Debug.Log("Unable to find " + path + ". Loading will crash, so aborting."); return; } string input; using(StreamReader sr = new StreamReader(path)) { input = sr.ReadToEnd(); } if(input != null) { //parse contents of file using(JsonTextReader reader = new JsonTextReader(new StringReader(input))) { while(reader.Read()) { if(reader.Value!=null) { if(reader.TokenType == JsonToken.PropertyName) { string property = (string)reader.Value; switch(property) { case "Sun": LoadLighting(reader); break; case "Ground": LoadTerrain(reader); break; case "Camera": LoadCamera(reader); break; case "Resources": LoadResources(reader); break; case "Players": LoadPlayers(reader); break; default: break; } } } } } } }
public static Color LoadColor(JsonTextReader reader) { if (reader == null) return new Color(0, 0, 0, 0); Color color = new Color(0, 0, 0, 0); string currVal = ""; while (reader.Read()) { if (reader.Value != null) { if (reader.TokenType == JsonToken.PropertyName) currVal = (string)reader.Value; else { switch (currVal) { case "r": color.r = (float)(double)reader.Value; break; case "g": color.g = (float)(double)reader.Value; break; case "b": color.b = (float)(double)reader.Value; break; case "a": color.a = (float)(double)reader.Value; break; default: break; } } } else if (reader.TokenType == JsonToken.EndObject) return color; } return color; }
private XmlNode DeserializeXmlNode(string json, string deserializeRootElementName) { JsonTextReader reader; reader = new JsonTextReader(new StringReader(json)); reader.Read(); XmlNodeConverter converter = new XmlNodeConverter(); if (deserializeRootElementName != null) converter.DeserializeRootElementName = deserializeRootElementName; XmlNode node = (XmlNode)converter.ReadJson(reader, typeof (XmlDocument), null, new JsonSerializer()); #if !NET20 string xmlText = node.OuterXml; reader = new JsonTextReader(new StringReader(json)); reader.Read(); XDocument d = (XDocument) converter.ReadJson(reader, typeof (XDocument), null, new JsonSerializer()); string linqXmlText = d.ToString(SaveOptions.DisableFormatting); if (d.Declaration != null) linqXmlText = d.Declaration + linqXmlText; Assert.AreEqual(xmlText, linqXmlText); #endif return node; }
public void Parse() { if (_IsParsed) return; var json = Encoding.UTF8.GetString(this.data); using (var strReader = new System.IO.StringReader(json)) { using (var r = new JsonTextReader(strReader)) { while (r.Read()) { if (r.TokenType == JsonToken.PropertyName) { switch (r.Value.ToString()) { case "client_quest": _AsQuestClient = r.ReadInt32Array(); break; case "coordinate": ParseCoordinate(r); break; case "quest": _Quests = r.ReadInt32Array(); break; case "shop": ParseShops(r); break; default: Console.Error.WriteLine("Unknown 'ENpcResident' data key: {0}", r.Value); throw new NotSupportedException(); } } } } } _IsParsed = true; }
static void Main(string[] args) { var reader = new StreamReader("testfile.json"); reader.ReadLine(); JsonTextReader rd = new Newtonsoft.Json.JsonTextReader(reader); var stream = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(stream); while (rd.Read()) { Console.WriteLine(rd.TokenType + "\t" + rd.Value); if (rd.TokenType == JsonToken.PropertyName) { var value = rd.Value.ToString(); if (value == "Chunks" || value == "SoundIntervals") { rd.Skip(); continue; } } writer.WriteToken(rd, false); } writer.Close(); Console.WriteLine(stream.GetStringBuilder().ToString()); }
public static List<Redirect> ReadRedirects(HttpContext context) { if (RedirectHandler.Redirects == null) { string path = WebConfigurationManager.AppSettings["redirects"] ?? "~/App_Data/redirects.json"; path = context.Server.MapPath(path); List<Redirect> newRedirects = new List<Redirect>(); using (TextReader file = File.OpenText(path)) using (JsonTextReader reader = new JsonTextReader(file)) { string from = null; while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { from = ((string)reader.Value).ToLowerInvariant(); } else if (reader.TokenType == JsonToken.String) { newRedirects.Add(new Redirect() { From = from, To = ((string)reader.Value).ToLowerInvariant() }); } } } RedirectHandler.Redirects = newRedirects; } return RedirectHandler.Redirects; }
public static void Load() { players.Clear(); string filename = "SavedGames" + Path.DirectorySeparatorChar + "Players.json"; if (File.Exists(filename)) { //read contents of file string input; using (StreamReader sr = new StreamReader(filename)) { input = sr.ReadToEnd(); } if (input != null) { //parse contents of file using (JsonTextReader reader = new JsonTextReader(new StringReader(input))) { while (reader.Read()) { if (reader.Value != null) { if (reader.TokenType == JsonToken.PropertyName) { if ((string)reader.Value == "Players") LoadPlayers(reader); } } } } } } }
public void Parse() { if (_IsParsed) return; var json = Encoding.UTF8.GetString(this.data); using (var strReader = new System.IO.StringReader(json)) { using (var r = new JsonTextReader(strReader)) { while (r.Read()) { if (r.TokenType == JsonToken.PropertyName) { switch (r.Value.ToString()) { case "region": ParseRegions(r); break; case "nonpop": _NonPops = r.ReadInt32Array(); break; case "item": _Items = r.ReadInt32Array(); break; case "instance_contents": _InstanceContents = r.ReadInt32Array(); break; default: Console.Error.WriteLine("Unknown 'BNpcName' data key: {0}", r.Value); throw new NotSupportedException(); } } } } } _IsParsed = true; }
public void NotificationConverter_ReadJsonCommentNotification_Equal() { var converter = new NotificationConverter(); var reader = new JsonTextReader(new StringReader(MockAccountEndpointResponses.GetCommentNotification)); reader.Read(); var serializer = new JsonSerializer(); var actual = (CommentNotification) converter.ReadJson(reader, typeof(CommentNotification), null, serializer); Assert.NotNull(actual); Assert.Equal(null, actual.AlbumCover); Assert.Equal("jasdev", actual.Author); Assert.Equal(3698510, actual.AuthorId); Assert.Equal(0, actual.Children.Count()); Assert.Equal("Reply test", actual.CommentText); Assert.Equal(new DateTimeOffset(new DateTime(2014, 07, 22, 23, 12, 54, DateTimeKind.Utc)), actual.DateTime); Assert.Equal(false, actual.Deleted); Assert.Equal(0, actual.Downs); Assert.Equal("VK9VqcM", actual.ImageId); Assert.Equal(false, actual.OnAlbum); Assert.Equal(3615, actual.ParentId); Assert.Equal(1, actual.Points); Assert.Equal(1, actual.Ups); Assert.Equal(3616, actual.Id); }
/// <summary> /// Returns a JSON string of your resulting query. If the user parameter contains a valid username /// the method will return the user information, including the 'id' which you can use against the /// other API endpoints in this class. /// </summary> /// <param name="user">Instagram username</param> /// <returns>string (json)</returns> public string getUserId(string user) { string output = ""; string url = "https://api.instagram.com/v1/users"; string urlRequest = "/search?q=" + user +"&access_token="; string accessToken = this.access_token; string fullUrl = url + urlRequest + accessToken; try { WebResponse response = processWebRequest(fullUrl); using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { JsonTextReader reader = new JsonTextReader(new StringReader(sr.ReadToEnd())); while (reader.Read()) { output += reader.Value; } } return output; } catch (Exception e) { return e.Message.ToString(); } }
public void YahooFinance() { string input = @"{ ""matches"" : [ {""t"":""C"", ""n"":""Citigroup Inc."", ""e"":""NYSE"", ""id"":""662713""} ,{""t"":""CHL"", ""n"":""China Mobile Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""660998""} ,{""t"":""PTR"", ""n"":""PetroChina Company Limited (ADR)"", ""e"":""NYSE"", ""id"":""664536""} ,{""t"":""RIO"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""671472""} ,{""t"":""RIOPR"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""3512643""} ,{""t"":""CSCO"", ""n"":""Cisco Systems, Inc."", ""e"":""NASDAQ"", ""id"":""99624""} ,{""t"":""CVX"", ""n"":""Chevron Corporation"", ""e"":""NYSE"", ""id"":""667226""} ,{""t"":""TM"", ""n"":""Toyota Motor Corporation (ADR)"", ""e"":""NYSE"", ""id"":""655880""} ,{""t"":""JPM"", ""n"":""JPMorgan Chase \\x26 Co."", ""e"":""NYSE"", ""id"":""665639""} ,{""t"":""COP"", ""n"":""ConocoPhillips"", ""e"":""NYSE"", ""id"":""1691168""} ,{""t"":""LFC"", ""n"":""China Life Insurance Company Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""688679""} ,{""t"":""NOK"", ""n"":""Nokia Corporation (ADR)"", ""e"":""NYSE"", ""id"":""657729""} ,{""t"":""KO"", ""n"":""The Coca-Cola Company"", ""e"":""NYSE"", ""id"":""6550""} ,{""t"":""VZ"", ""n"":""Verizon Communications Inc."", ""e"":""NYSE"", ""id"":""664887""} ,{""t"":""AMX"", ""n"":""America Movil S.A.B de C.V. (ADR)"", ""e"":""NYSE"", ""id"":""665834""}], ""all"" : false } "; using (JsonReader jsonReader = new JsonTextReader(new StringReader(input))) { while (jsonReader.Read()) { Console.WriteLine(jsonReader.Value); } } }
/// <summary> /// Parses the json string and returns a Dictionary of verification pairs /// </summary> /// <param name="verificationFormatJSON"></param> /// <returns></returns> public static Dictionary<string, object> BuildVerifyDictionary(string verificationFormatJSON) { bool isStringValid = ValidateJsonString(verificationFormatJSON); // Immediately fail if the string format is not valid Validity.Assert(isStringValid); Dictionary<string, object> verification = new Dictionary<string, object>(); JsonTextReader reader = new JsonTextReader(new StringReader(verificationFormatJSON)); while (reader.Read()) { // Start of new item if (reader.TokenType == JsonToken.StartObject) { // Start of new entry // Ignore and move to the entry pair } else if (reader.TokenType == JsonToken.PropertyName) { KeyValuePair<string, object> pair = GetVerifyPair(reader); if (verification.ContainsKey(pair.Key)) { verification[pair.Key] = pair.Value; } else { verification.Add(pair.Key, pair.Value); } } } return verification; }
public override void WriteRawJsonToken( JsonTokenType jsonTokenType, ReadOnlySpan <byte> rawJsonToken) { string rawJson = Encoding.UTF8.GetString(rawJsonToken); Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(new StringReader(rawJson)) { DateParseHandling = DateParseHandling.None, }; while (jsonTextReader.Read()) { if (jsonTokenType == JsonTokenType.FieldName) { this.writer.WritePropertyName(jsonTextReader.Value as string); } else { switch (jsonTextReader.TokenType) { case Newtonsoft.Json.JsonToken.StartObject: this.writer.WriteStartObject(); break; case Newtonsoft.Json.JsonToken.StartArray: this.writer.WriteStartArray(); break; case Newtonsoft.Json.JsonToken.PropertyName: this.writer.WritePropertyName(jsonTextReader.Value as string); break; case Newtonsoft.Json.JsonToken.Integer: case Newtonsoft.Json.JsonToken.Float: case Newtonsoft.Json.JsonToken.String: case Newtonsoft.Json.JsonToken.Boolean: this.writer.WriteValue(jsonTextReader.Value); break; case Newtonsoft.Json.JsonToken.Null: this.writer.WriteNull(); break; case Newtonsoft.Json.JsonToken.EndObject: this.writer.WriteEndObject(); break; case Newtonsoft.Json.JsonToken.EndArray: this.writer.WriteEndArray(); break; default: throw new ArgumentOutOfRangeException($"Unknown {nameof(JsonToken)}: {jsonTextReader.TokenType}."); } } } }
protected System.Collections.Generic.IEnumerable <JsonLogEntry> GetEntries() { Newtonsoft.Json.JsonSerializer oJsonSerializer = new Newtonsoft.Json.JsonSerializer(); foreach (System.Tuple <string, System.IO.Stream> st in StreamFactory.GetStreams(From, this.Recurse)) { this.StreamLineNumber = 0; this.CurrentStreamName = st.Item1; this.RecordIndex = 0; using (AdvancedTextReader srdr = new AdvancedTextReader(st.Item2, this.TextReaderOptions)) { using (var m_JsonReader = new Newtonsoft.Json.JsonTextReader(srdr) { SupportMultipleContent = true }) { bool bStartRead = string.IsNullOrEmpty(JsonPropertyToRead); while (m_JsonReader.Read()) { if (!bStartRead && !(m_JsonReader.TokenType == JsonToken.PropertyName && m_JsonReader.Value == JsonPropertyToRead)) { continue; } else { bStartRead = true; } if (m_JsonReader.TokenType == JsonToken.StartObject) { // Additional fields this.StreamLineNumber = m_JsonReader.LineNumber; this.RecordIndex += 1; // Deserialize entries and yield JsonLogEntry le = oJsonSerializer.Deserialize <JsonLogEntry>(m_JsonReader); yield return(le); } } } } } }
protected override void InitValueExtractor() { // Init value extractor from first record ValueExtractor = new DictionaryExtractor(new string[] { }); // init empty first if can't init later Newtonsoft.Json.JsonSerializer oJsonSerializer = new Newtonsoft.Json.JsonSerializer(); foreach (var st in StreamFactory.GetStreams(this.From, this.Recurse)) // returns touplse (stream name as string, Stream object implementaion) { using (AdvancedTextReader srdr = new AdvancedTextReader(st.Item2, this.TextReaderOptions)) { using (var m_JsonReader = new Newtonsoft.Json.JsonTextReader(srdr) { SupportMultipleContent = true }) { bool bStartRead = string.IsNullOrEmpty(JsonPropertyToRead); while (m_JsonReader.Read()) { if (!bStartRead && !(m_JsonReader.TokenType == JsonToken.PropertyName && m_JsonReader.Value == JsonPropertyToRead)) { continue; } else { bStartRead = true; } if (m_JsonReader.TokenType == JsonToken.StartObject) { // Deserialize JsonLogEntry logentry = oJsonSerializer.Deserialize <JsonLogEntry>(m_JsonReader); // Set the value extractor from the first JSON record and exit ValueExtractor = new DictionaryExtractor(logentry); break; } } } } } }
public void DeserializeRequest(Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] rawBody = bodyReader.ReadContentAsBase64(); MemoryStream ms = new MemoryStream(rawBody); StreamReader sr = new StreamReader(ms); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); if (parameters.Length == 1) { string contenido = sr.ReadToEnd(); if (contenido.StartsWith("{\"Querye\":")) { contenido = contenido.Substring("{\"Querye\":".Length); contenido = contenido.Substring(0, contenido.Length - 1); } // single parameter, assuming bare parameters[0] = JsonConvert.DeserializeObject(contenido, operation.Messages[0].Body.Parts[0].Type); } else { // multiple parameter, needs to be wrapped Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr); reader.Read(); if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject) { throw new InvalidOperationException("Input needs to be wrapped in an object"); } reader.Read(); while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { string parameterName = reader.Value as string; reader.Read(); if (this.parameterNames.ContainsKey(parameterName)) { int parameterIndex = this.parameterNames[parameterName]; parameters[parameterIndex] = serializer.Deserialize(reader, this.operation.Messages[0].Body.Parts[parameterIndex].Type); } else { reader.Skip(); } reader.Read(); } reader.Close(); } sr.Close(); ms.Close(); }
/* Makes a request for realtime data * Called with the assumption that there is a valid auth token * Requests should ask for 15 seconds of data every 15 seconds * Example request * https://api.hexoskin.com/api/data/?user=14052&datatype=18&start=392531420416&end=392541193472&no_timestamps=exact * * Request URL: https://api.hexoskin.com/api/data/ * User you are requesting data for: user=14052 * In addition to requesting for a specific user's data you can request for a specific record if you have the recordID using record=23409 * Starting point for timeframe of data: start=392531420416 * Ending point for timeframe of data: end=392541193472 * End time can be omitted to pull all available data from startpoint onwards * Filter: no_timestamps=exact * This filter is just one of many filters you could use, this is not needed for the request to work but makes trims down some of the data */ private IEnumerator RealTimeRequest() { //Set up csv files for writing String filePath = Application.dataPath + "/Resources/Visualizations/RR.csv"; String filePathB = Application.dataPath + "/Resources/Visualizations/Breathing.csv"; StreamWriter writer = new StreamWriter(filePath); StreamWriter writerB = new StreamWriter(filePathB); writer.WriteLine("Timestamp (Minutes),RR Interval"); writerB.WriteLine("Timestamp (Minutes),Breathing"); //Set current timestamp for realtime request, need to multiply this by 256 before request to be in line with Hexoskin's timestamping TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); ulong secondsSinceEpoch = (ulong)t.TotalSeconds; startTime = secondsSinceEpoch; currentTime = secondsSinceEpoch; float valueAvg; int numValues; //Get data from x seconds ago currentTime = currentTime - DELAY; ulong currentHexoTime; ulong endHexoTime; endTime = startTime + 86400; //End time 24 hours from then endHexoTime = endTime * 256; //By this point valid auth token has been given Repeat call every 15 seconds //Have to use while true with a sleep in order to continuing calling every 15 seconds while (true) { currentHexoTime = currentTime * 256; //This request will return a flat array of values without timestamps for the requested datatype //datatype here refers to what data we want from the record we are looking at. 18 is RR interval and 33 is breathing rate String realTimeReqURI = "https://api.hexoskin.com/api/data/?datatype=18" + "&start=" + currentHexoTime.ToString() + "&record=" + RECORDID; //+ "&end=" + endHexoTime.ToString(); String realTimeBreathURI = "https://api.hexoskin.com/api/data/?datatype=33" + "&start=" + currentHexoTime.ToString() + "&record=" + RECORDID; //+ "&end=" + endHexoTime.ToString(); /* Request for RR interval data */ using (UnityWebRequest realTimeReq = UnityWebRequest.Get(realTimeReqURI)) { DownloadHandler dH = new DownloadHandlerBuffer(); realTimeReq.downloadHandler = dH; realTimeReq.chunkedTransfer = false; realTimeReq.SetRequestHeader("Authorization", "Bearer " + AUTHTOKEN); yield return(realTimeReq.SendWebRequest()); //Check for errors if (realTimeReq.isNetworkError || realTimeReq.isHttpError) { print("Refresh error " + realTimeReq.error); print(dH.text); } else { valueAvg = 0.0f; numValues = 0; string output = realTimeReq.downloadHandler.text; print("Response: " + realTimeReq.downloadHandler.text); string temp; Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new StringReader(output)); //This code here parses the response for values and averages the values for use in adjusting the UI indicator bool next = false; //Track next value double stampTemp = 0; while (reader.Read()) { if (reader.Value != null && reader.TokenType.ToString() == "Float") { temp = reader.Value.ToString(); if (!next && temp != "18") { //Timestamp stampTemp = ulong.Parse(temp); stampTemp = stampTemp / 256; stampTemp = stampTemp - startTime; next = true; } else if (next && temp != "18") { if (stampTemp > 0.0) { //If timestamp if within the simulation starting stampTemp = stampTemp / 60; temp = Math.Round(float.Parse(temp), 2).ToString(); writer.WriteLine(stampTemp + "," + temp); writer.Flush(); valueAvg = valueAvg + float.Parse(temp); numValues++; } next = false; } } } valueAvg = valueAvg / numValues; //Adjust HUD if (valueAvg <= 0.4) { //Red GIcon.CrossFadeAlpha(0, 1.0f, false); YIcon.CrossFadeAlpha(0, 1.0f, false); RIcon.CrossFadeAlpha(1, 2.0f, false); } else if (valueAvg > 0.4 && valueAvg <= 0.55) { //Yellow GIcon.CrossFadeAlpha(0, 1.0f, false); YIcon.CrossFadeAlpha(1, 2.0f, false); RIcon.CrossFadeAlpha(0, 1.0f, false); } else { //Green GIcon.CrossFadeAlpha(1, 2.0f, false); YIcon.CrossFadeAlpha(0, 1.0f, false); RIcon.CrossFadeAlpha(0, 1.0f, false); } print(valueAvg); } } /* Request for breathing data */ //This section does the same as the RR interval section but for breathing rate. //This section also only writes data to the csv and doesn't have any UI adjustments using (UnityWebRequest realTimeReq = UnityWebRequest.Get(realTimeBreathURI)) { DownloadHandler dH = new DownloadHandlerBuffer(); realTimeReq.downloadHandler = dH; realTimeReq.chunkedTransfer = false; realTimeReq.SetRequestHeader("Authorization", "Bearer " + AUTHTOKEN); yield return(realTimeReq.SendWebRequest()); //Check for errors if (realTimeReq.isNetworkError || realTimeReq.isHttpError) { print("Refresh error " + realTimeReq.error); print(dH.text); } else { string output = realTimeReq.downloadHandler.text; print("Response: " + realTimeReq.downloadHandler.text); string temp; Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new StringReader(output)); bool next = false; //Track next value double stampTemp = 0; string prevValue = null; while (reader.Read()) { if (reader.Value != null && reader.TokenType.ToString() == "Float") { temp = reader.Value.ToString(); if (!next && temp != "33") { //Timestamp stampTemp = ulong.Parse(temp); stampTemp = stampTemp / 256; stampTemp = stampTemp - startTime; next = true; } else if (next && temp != "33") { if (stampTemp > 0.0) { //If timestamp if within the simulation starting stampTemp = stampTemp / 60; prevValue = temp; if (ulong.Parse(temp) > 10000) { if (ulong.Parse(prevValue) > 10000) { //if first value is null toss out } else { //If current value is null writerB.WriteLine(stampTemp + "," + prevValue); writerB.Flush(); } } else { writerB.WriteLine(stampTemp + "," + temp); writerB.Flush(); } } next = false; } } } } } yield return(new WaitForSeconds(DELAY)); currentTime = currentTime + DELAY; } writer.Close(); }
private void filterGeoPosition(String fileName, double minX, double maxX, double minY, double maxY) { var jsonDoc = ""; var batch = new List <string>(); var boundingBox = new NetTopologySuite.Geometries.Envelope(minX, maxX, minY, maxY); var feature = new NetTopologySuite.Features.Feature(); using (FileStream s = File.Open(fileName, FileMode.Open)) using (var streamReader = new StreamReader(s)) { var file = Path.GetFileNameWithoutExtension(fileName).Split("."); var topicname = file[1]; using (var jsonreader = new Newtonsoft.Json.JsonTextReader(streamReader)) { while (jsonreader.Read()) { var reader = new NetTopologySuite.IO.GeoJsonReader(); if (jsonreader.TokenType == Newtonsoft.Json.JsonToken.StartObject) { while (jsonreader.Read()) { if (jsonreader.TokenType == Newtonsoft.Json.JsonToken.StartArray) { while (jsonreader.Read()) { try { if (jsonreader != null) { feature = reader.Read <NetTopologySuite.Features.Feature>(jsonreader); } var geo = feature.Geometry; var atr = feature.Attributes; if (boundingBox.Intersects(geo.EnvelopeInternal)) { jsonDoc = createGeoObject(atr, geo); batch.Add(jsonDoc); if (batch.Count >= 5000) { _producer.Produce(topicname, batch); _logger.LogInformation("Wrote " + batch.Count + " objects into " + topicname); batch.Clear(); } } } //Loop gives reader exception when it reaches the last element from the file catch (Newtonsoft.Json.JsonReaderException e) { _logger.LogError("Error writing data: {0}.", e.GetType().Name); var geo = feature.Geometry; var atr = feature.Attributes; jsonDoc = createGeoObject(atr, geo); batch.Add(jsonDoc); _producer.Produce(topicname, batch); _logger.LogInformation("Wrote " + batch.Count + " objects into " + topicname); batch.Clear(); break; } } } } } if (batch != null) { _producer.Produce(topicname, batch); _logger.LogInformation("Wrote " + batch.Count + " objects into " + topicname); batch.Clear(); } } } } }
private void TcpListenerCallback(IAsyncResult result) { // read incoming tcp message tcpContext = tcpListener.EndAcceptTcpClient(result); StreamReader tcpStreamReader = new StreamReader(tcpContext.GetStream()); while (true) { incomingTcpMessage = tcpStreamReader.ReadLine().Trim(); /* TODO: Support more than 2 servos & take in any actuators*/ float[] servoValues = new float[2]; int currentId = -1; bool willTurnWholeRobot = false; float degreesToTurnRobot = 0; /* Parse incoming tcp message from JSON */ Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(new StringReader(incomingTcpMessage)); while (jsonTextReader.Read()) { // READ SERVO INPUTS if (jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.PropertyName) && jsonTextReader.Value.Equals("servos")) { while (!jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.EndArray)) { // Get if speed value is a turn if (jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.PropertyName) && jsonTextReader.Value.Equals("isTurn")) { jsonTextReader.Read(); if (jsonTextReader.Value != null) { bool isTurn = bool.Parse(jsonTextReader.Value.ToString()); // servo id = -1; turn the robot at specified degree via servoSpeed if (currentId == -1) { if (isTurn) { willTurnWholeRobot = true; } else { willTurnWholeRobot = false; } } } } else { jsonTextReader.Read(); } // Get ServoId if (jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.PropertyName) && jsonTextReader.Value.Equals("servoId")) { jsonTextReader.Read(); if (jsonTextReader.Value != null && jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.Integer)) { currentId = int.Parse(jsonTextReader.Value.ToString()) % 2; // TODO: Fix action profile maping to 0 and 1 index } } // Get ServoSpeed if (jsonTextReader.TokenType.Equals(Newtonsoft.Json.JsonToken.PropertyName) && jsonTextReader.Value.Equals("servoSpeed")) { jsonTextReader.Read(); if (jsonTextReader.Value != null) { // servo id = -1; turn the robot at specified degree via servoSpeed if (currentId == -1) { degreesToTurnRobot = float.Parse(jsonTextReader.Value.ToString()); } else { float servoSpeed = float.Parse(jsonTextReader.Value.ToString()); servoValues[currentId] += servoSpeed; } } } } // end servos array } // end servos property } // end json reader /*TODO: Map correct motor actions to proper servo values*/ if (willTurnWholeRobot) { currentControlIndex = ACTION_PROFILE_TURN; currentTurnDegreeProfile = degreesToTurnRobot; } else if (degreesToTurnRobot > 0) { currentControlIndex = ACTION_PROFILE_FORWARD; } else if (degreesToTurnRobot < 0) { currentControlIndex = ACTION_PROFILE_BACKWARD; } else if (degreesToTurnRobot == 0) { currentControlIndex = ACTION_PROFILE_STOP; } else { // left side + | right side - | => GO RIGHT if (servoValues[0] > 0 && servoValues[1] <= 0) { currentControlIndex = ACTION_PROFILE_RIGHT; } // left side - | right side + | => GO LEFT else if (servoValues[0] <= 0 && servoValues[1] > 0) { currentControlIndex = ACTION_PROFILE_LEFT; } // left side + | right side + | => GO FORWARD else if (servoValues[0] > 0 && servoValues[1] > 0) { currentControlIndex = ACTION_PROFILE_FORWARD; } // left side - | right side - | => GO BACKWARD else if (servoValues[0] < 0 && servoValues[1] < 0) { currentControlIndex = ACTION_PROFILE_BACKWARD; } } /* * OPEN OUTPUT STREAM AND WRITE ROBOT STATUS */ String output2 = robotBean.toJSON() + "\n"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(robotBean.toJSON().Trim() + "\n"); output = tcpContext.GetStream(); output.Write(buffer, 0, buffer.Length); } }
public static string JsonFormat(string json) { try { StringReader sr = new StringReader(json); Newtonsoft.Json.JsonTextReader tr = new Newtonsoft.Json.JsonTextReader(sr); StringBuilder sb = new StringBuilder(); bool hasInArray = false; bool hasPropertyStart = false; while (tr.Read()) { switch (tr.TokenType) { case Newtonsoft.Json.JsonToken.Boolean: if (hasInArray) { sb.AppendFormat("{0},", (bool)tr.Value ? "true" : "false"); } else { sb.AppendFormat("{0}", (bool)tr.Value ? "true" : "false"); } break; case Newtonsoft.Json.JsonToken.Bytes: break; case Newtonsoft.Json.JsonToken.Comment: break; case Newtonsoft.Json.JsonToken.Date: sb.AppendFormat("\"{0}\"", string.Format("{0:s}.{0:fffffff}{0:zzz}", tr.Value)); break; case Newtonsoft.Json.JsonToken.EndArray: hasInArray = false; sb.Remove(sb.Length - 1, 1); sb.Append("]"); break; case Newtonsoft.Json.JsonToken.EndConstructor: break; case Newtonsoft.Json.JsonToken.EndObject: sb.Append("}"); break; case Newtonsoft.Json.JsonToken.Float: if (hasInArray) { sb.AppendFormat("{0},", tr.Value); } else { sb.AppendFormat("{0}", tr.Value); } break; case Newtonsoft.Json.JsonToken.Integer: if (hasInArray) { sb.AppendFormat("{0},", tr.Value); } else { sb.AppendFormat("{0}", tr.Value); } break; case Newtonsoft.Json.JsonToken.None: break; case Newtonsoft.Json.JsonToken.Null: sb.Append("null"); break; case Newtonsoft.Json.JsonToken.PropertyName: if (hasPropertyStart) { sb.AppendFormat("\"{0}\":", tr.Value); } else { sb.AppendFormat(",\"{0}\":", tr.Value); } hasPropertyStart = false; break; case Newtonsoft.Json.JsonToken.Raw: break; case Newtonsoft.Json.JsonToken.StartArray: hasInArray = true; sb.Append("["); break; case Newtonsoft.Json.JsonToken.StartConstructor: break; case Newtonsoft.Json.JsonToken.StartObject: hasPropertyStart = true; sb.Append("{"); break; case Newtonsoft.Json.JsonToken.String: if (hasInArray) { sb.AppendFormat("\"{0}\",", tr.Value); } else { sb.AppendFormat("\"{0}\"", tr.Value); } break; case Newtonsoft.Json.JsonToken.Undefined: break; default: break; } } return(sb.ToString()); } catch { } return(json); }