static void Main(string[] args) { StreamReader sr = new StreamReader(Console.OpenStandardInput()); string input = sr.ReadToEnd(); sr.Dispose(); JavaScriptSerializer ser = new JavaScriptSerializer(); dynamic json = ser.DeserializeObject(input); for (int i = 1; i < json.Length; i++) { dynamic block = json[i]; string blockType = block[0]; Dictionary<string, object> blockAttr = block[1]; for (int j = 2; j < block.Length; j++) { dynamic span = block[j]; string spanType = span[0]; string text = span[1]; Console.Write(text); } Console.WriteLine(); Console.WriteLine(); } }
protected void ParentsSectionChat_Click(object sender, EventArgs e) { JavaScriptSerializer json_serializer = new JavaScriptSerializer(); var tempMessageCount = 0; var actualMessageCount = 0; //Put ur db logic to get channel name' //foreach (var item in collection) //{ var channel = "fcf173dc-5d2c-4e1a-80a5-b92068d91019"; tempMessageCount = 0; actualMessageCount = 0; //Your total message count string content = GetHistoryContent(channel); if (content.Length > 47) { var messageList = json_serializer.DeserializeObject(content.Substring(1, content.Length - 38)); tempMessageCount = ((object[])messageList).Count(); actualMessageCount = tempMessageCount; while (tempMessageCount == 100) { var startCounter = content.Substring(content.Length - 36, 17); var morecontent = GetHistoryContent(channel, startCounter); if (content.Length > 47) { var moreMessageList = json_serializer.DeserializeObject(content.Substring(1, content.Length - 38)); tempMessageCount = ((object[])moreMessageList).Count(); actualMessageCount = actualMessageCount + tempMessageCount; } } } //} }
public void TestMethod1() { string jsonstr = "{x:11,y:'abcd'}"; JavaScriptSerializer serializer = new JavaScriptSerializer(); object obj = serializer.DeserializeObject(jsonstr); Dictionary<string, object> dic = serializer.DeserializeObject(jsonstr) as Dictionary<string, object>; dd d = serializer.Deserialize<dd>(jsonstr); }
void SerializeData() { for (Int32 i = 0; i < _content.Count; i++) { String line = GetFixedLine(i); Match match = Defines.GetDataRegex(_typeId, _subTypeId).Match(line); if (match.Success) { JavaScriptSerializer json = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue }; if (line.Contains("_totalCount")) TotalCount = UInt32.Parse(Defines.GetStringBetweenTwoOthers(line, "_totalCount: ", ",")); else TotalCount = 0; Objects = (Object[])json.DeserializeObject(match.Groups[1].Captures[0].Value); } } if (Objects == null) Objects = new Object[0]; }
public static List<string> GeocodeGoogle(string postcode) { var longlat = new List<string>(); var req = (HttpWebRequest)WebRequest.Create(string.Format("http://www.google.com/uds/GlocalSearch?q={0}&v=1.0", postcode)); using (var resp = req.GetResponse()) using (var respStream = resp.GetResponseStream()) using (var reader = new StreamReader(respStream, System.Text.Encoding.UTF8, true)) { var response = reader.ReadToEnd(); var serializer = new JavaScriptSerializer(); var deserialized = (Dictionary<string, object>)serializer.DeserializeObject(response); var responseData = (Dictionary<string, object>)deserialized["responseData"]; var results = (object[])responseData["results"]; try { var resultsData = (Dictionary<string, object>)results[0]; longlat.Add(resultsData["lat"].ToString()); longlat.Add(resultsData["lng"].ToString()); longlat.Add(resultsData["title"].ToString()); } catch (Exception) { longlat.Add("0"); longlat.Add("0"); longlat.Add("No Result"); } return longlat; } }
public async Task<string> GetSetInfo(string sourceId, string set) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) filter = sobj["setFilter"]; switch (type) { case EntitySetType.User: { UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } case EntitySetType.Role: { RoleServiceProxy svc = new RoleServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } } } return null; }
public void ShouldAddGrants() { var token = new AccessToken("AC456", "SK123", "foobar"); var delta = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var timestamp = (int)Math.Floor(delta.TotalSeconds); token.AddGrant(new ConversationsGrant()); token.AddGrant(new IpMessagingGrant()); var encoded = token.ToJWT(); Assert.IsNotNull(encoded); Assert.IsNotEmpty(encoded); var decoded = JsonWebToken.Decode(encoded, "foobar"); Assert.IsNotEmpty(decoded); var serializer = new JavaScriptSerializer(); var payload = (Dictionary<string, object>)serializer.DeserializeObject(decoded); Assert.IsNotNull(payload); Assert.AreEqual("SK123", payload["iss"]); Assert.AreEqual("AC456", payload["sub"]); var exp = Convert.ToInt64(payload["exp"]); Assert.AreEqual(timestamp + 3600, exp); var jti = (string)payload["jti"]; Assert.AreEqual("SK123-" + timestamp.ToString(), jti); var grants = (Dictionary<string, object>)payload["grants"]; Assert.AreEqual(2, grants.Count); Assert.IsNotNull(grants["rtc"]); Assert.IsNotNull(grants["ip_messaging"]); }
public ActionResult BookmarkDonor(int accountId) { if (!Request.IsAuthenticated) { return RedirectToAction("LogOn", "Account"); } else { Models.BookmarkedDonor book = new MPXMobile.Models.BookmarkedDonor(); book.Donor_ID = accountId; book.User_ID = HttpContext.User.Identity.Name; var status = Models.Donors.BookmarkDonor(book); ViewData["BookmarkedDonors"] = status; if (IsAjaxRequest()) { string message = string.Empty; JavaScriptSerializer serializer = new JavaScriptSerializer(); object jsonData = serializer.DeserializeObject(status.ToString()); return Json(new { jsonData }); } else { return RedirectToAction("BookmarkedDonors", "Home"); } } }
public void ShouldHaveNbf() { var token = new AccessToken("AC456", "SK123", "foobar"); var now = DateTime.UtcNow; token.Nbf = AccessToken.ConvertToUnixTimestamp(now); var delta = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var timestamp = (int)Math.Floor(delta.TotalSeconds); var encoded = token.ToJWT(); Assert.IsNotNull(encoded); Assert.IsNotEmpty(encoded); var decoded = JsonWebToken.Decode(encoded, "foobar"); Assert.IsNotEmpty(decoded); var serializer = new JavaScriptSerializer(); var payload = (Dictionary<string, object>)serializer.DeserializeObject(decoded); Assert.IsNotNull(payload); Assert.AreEqual("SK123", payload["iss"]); Assert.AreEqual("AC456", payload["sub"]); Assert.AreEqual(AccessToken.ConvertToUnixTimestamp(now), payload["nbf"]); var exp = Convert.ToInt64(payload["exp"]); Assert.AreEqual(timestamp + 3600, exp); var jti = (string)payload["jti"]; Assert.AreEqual("SK123-" + timestamp.ToString(), jti); var grants = (Dictionary<string, object>)payload["grants"]; Assert.AreEqual(0, grants.Count); }
private String toJSON(string[] response) { JavaScriptSerializer serializer = new JavaScriptSerializer(); foreach (var str in response) { if (String.IsNullOrEmpty(str)) continue; var json = serializer.DeserializeObject(str); if (!(json is IDictionary<string, object>)) continue; IDictionary<string, object> dict = (IDictionary<string, object>)json; var results = (object[])dict["result"]; if (results == null || results.Length == 0) continue; var result = (IDictionary<string, object>)results[0]; var alts = (object[])result["alternative"]; if (alts == null || alts.Length == 0) continue; var alt = (IDictionary<string, object>)alts[0]; WSRConfig.GetInstance().logDebug("[Google Recognize]", "toJSON: " + alt["confidence"] + " : " + alt["transcript"]); return (string)alt["transcript"]; } return ""; }
public static object DeserializeJSONCollectionFile(string filePath) { JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); Assembly assembly = Assembly.GetExecutingAssembly(); string collectionToCreate = string.Empty; using (StreamReader sr = new StreamReader(assembly.GetManifestResourceStream(filePath))) { collectionToCreate = sr.ReadToEnd(); } Dictionary<string, object> collectionDictionary = javaScriptSerializer.DeserializeObject(collectionToCreate) as Dictionary<string, object>; string collectionTypeString = collectionDictionary.Keys.First(); Type collectionType = Type.GetType(collectionTypeString); object result = Activator.CreateInstance(collectionType); object[] objectArray = collectionDictionary.First().Value as object[]; foreach (object o in objectArray) { Dictionary<string, object> objectDictionary = (Dictionary<string, object>)o; string objectTypeString = objectDictionary.Keys.First(); Type objectType = Type.GetType(objectTypeString); object objectToAdd = Activator.CreateInstance(objectType); Dictionary<string, object> properties = objectDictionary.First().Value as Dictionary<string, object>; YellowstonePathology.Business.Persistence.JSONReaderPropertyWriter jsonReaderPropertyWriter = new Persistence.JSONReaderPropertyWriter(objectToAdd, properties); jsonReaderPropertyWriter.WriteProperties(); result.GetType().GetMethod("Add").Invoke(result, new Object[] { objectToAdd }); } return result; }
private void UpdateReadings() { // Create a request for the URL. WebRequest request = WebRequest.Create("http://api.thingspeak.com/channels/26429/feed/last.json"); // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Display the status. Console.WriteLine(response.StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. JavaScriptSerializer deserializer = new JavaScriptSerializer(); Dictionary<string, object> data = (Dictionary<string, object>)deserializer.DeserializeObject(responseFromServer); lblStoveTemp.Text = (String)data["field1"]; lblAmbientTemp.Text = (String)data["field2"]; lblDamper.Text = (String)data["field3"]; DateTime toDateTime = DateTime.Parse((String)data["created_at"]); lblTime.Text = toDateTime.AddHours(1).ToShortTimeString(); // Cleanup the streams and the response. reader.Close(); dataStream.Close(); response.Close(); }
public static bool Get_Launch_Specific_Data() { try { if (Utils.is_amazon_machine) { string sURL = "http://169.254.169.254/latest/user-data/"; WebRequest wrGETURL; wrGETURL = WebRequest.Create(sURL); WebProxy myProxy = new WebProxy("myproxy", 80); myProxy.BypassProxyOnLocal = true; Stream objStream; objStream = wrGETURL.GetResponse().GetResponseStream(); StreamReader sr = new StreamReader(objStream); user_Data_String = sr.ReadToEnd(); } Console.WriteLine("user_Data_String="+user_Data_String); JavaScriptSerializer serializer = new JavaScriptSerializer(); CFG = serializer.DeserializeObject(user_Data_String) as Dictionary<string, object>; } catch (Exception e) { Console.WriteLine("Excpetion in Get_Launch_Specific_Data(). = " + e.Message); return false; } return true; }
// cloud only public AutomationConnection(Connection cloudConnection, ConnectionType cloudConnectionType) : base(cloudConnection.Name, null, cloudConnection.Properties.LastModifiedTime.LocalDateTime) { this.ConnectionType = cloudConnectionType.Name; JavaScriptSerializer jss = new JavaScriptSerializer(); this.ValueFields = new Dictionary<string, Object>(); foreach(KeyValuePair<string, string> field in cloudConnection.Properties.FieldDefinitionValues) { if(cloudConnectionType.Properties.FieldDefinitions[field.Key].Type.Equals(AutomationISE.Model.Constants.ConnectionTypeFieldType.String)) { this.ValueFields.Add(field.Key, field.Value); } else { try { var value = jss.DeserializeObject(field.Value.ToLower()); this.ValueFields.Add(field.Key, value); } catch { this.ValueFields.Add(field.Key, field.Value); } } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // // Get a shortcut to context objects // var request = filterContext.HttpContext.Request; var server = filterContext.HttpContext.Server; string contentType = request.ContentType; if (string.IsNullOrEmpty(contentType)) return; if (!contentType.Contains("application/json")) return; string paramValue = request.QueryString.ToString(); if (request.RequestType == "GET") paramValue = server.UrlDecode(paramValue); else using (var reader = new StreamReader(request.InputStream)) paramValue = reader.ReadToEnd(); var serializer = new JavaScriptSerializer(); var rawResult = (IDictionary<string, object>)serializer.DeserializeObject(paramValue); foreach (var item in filterContext.ActionDescriptor.GetParameters()) { var deserializeMethod = serializer.GetType() .GetMethods().First(m => m.Name == "ConvertToType") .MakeGenericMethod(item.ParameterType); filterContext.ActionParameters[item.ParameterName] = deserializeMethod.Invoke(serializer, new[] { rawResult[item.ParameterName] }); } }
public static async Task<string> GetSetInfo(string adminId, string set) { EntitySetType type; JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) filter = sobj["setFilter"]; switch (type) { case EntitySetType.User: { var p = await GetMaxPriority(adminId); UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(Cntx, filter); RoleServiceProxy rsvc = new RoleServiceProxy(); var roles = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null); List<dynamic> rlist = new List<dynamic>(); foreach (var r in roles) { if (r.RolePriority <= p.Major) rlist.Add(new { id = r.ID, name = r.RoleName, path = r.DistinctString, op = true }); } JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters, roles = rlist.ToArray() }); return json; } } } return null; }
/// <summary> /// Parses a JSON string into the current <see cref="Response"/>. /// </summary> /// <param name="jsonResponse">The JSON string to transform.</param> /// <param name="result">The parsed result.</param> /// <returns>True if no errors were encountered during parsing, or false if the JSON appeared to be malformed.</returns> public static bool TryParseJson(string jsonResponse, out Response result) { JavaScriptSerializer jss = new JavaScriptSerializer(); dynamic deserializedJson = jss.DeserializeObject(jsonResponse); Response resultResponse = new Response(); if (!deserializedJson.ContainsKey("success")) { result = null; return false; } resultResponse._success = deserializedJson["success"]; resultResponse._errors = Errors.None; if (deserializedJson.ContainsKey("error-codes")) { Errors? errors = ErrorsToEnum(deserializedJson["error-codes"]); if (!errors.HasValue) { result = null; return false; } resultResponse._errors = errors.Value; } result = resultResponse; return true; }
private void requestButton_Click(object sender, EventArgs e) { const string requestUri = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5/"; StringBuilder data = new StringBuilder(); data.AppendFormat("query?text={0}&geometry={1}&geometryType={2}&inSR={3}", string.Empty, string.Empty, "esriGeometryPoint", string.Empty); data.AppendFormat("&spatialRel-{0}&relationParam={1}&objectIds={2}", "esriSpatialRelIntersects", string.Empty, string.Empty); data.AppendFormat("&where={0}", System.Web.HttpUtility.UrlEncode("POP2000>" + MyNumericUpDown.Value.ToString(CultureInfo.InvariantCulture))); data.AppendFormat("&time={0}&returnCountOnly={1}&returnIdsOnly={2}&returnGeometry={3}", string.Empty, "false", "false", "false"); data.AppendFormat("&maxAllowableOffset={0}&outSR={1}&outFields={2}&f={3}", string.Empty, string.Empty, "*", "json"); HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); // JavaScriptSerializer in System.Web.Extensions.dll JavaScriptSerializer jss = new JavaScriptSerializer(); IDictionary<string, object> results = jss.DeserializeObject(responseString) as IDictionary<string, object>; if (results == null || !results.ContainsKey("features")) return; IEnumerable<object> features = results["features"] as IEnumerable<object>; foreach (IDictionary<string, object> record in from IDictionary<string, object> feature in features select feature["attributes"] as IDictionary<string, object>) { MyDataGridView.Rows.Add(new[] {record["ObjectID"], record["STATE_NAME"], record["POP2000"]}); } MyDataGridView.Update(); } }
public Object QueryDuoApi(IHttpWebRequestFactory webRequestFactory, string protocol, string path, HttpWebRequestMethod method, IEnumerable<KeyValuePair<string, string>> queryValues) { var duoWebRequest = CreateSignedDuoWebRequest(webRequestFactory, protocol, path, method, queryValues); try { var duoResponse = duoWebRequest.GetResponse(); if (duoResponse != null) { var responseStream = duoResponse.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { var js = new JavaScriptSerializer(); var objText = reader.ReadToEnd(); return js.DeserializeObject(objText); } } } } catch (WebException exception) { return null; } return null; }
public Manager_Form(String scene_params_json) { InitializeComponent(); JavaScriptSerializer serializer = new JavaScriptSerializer(); var temp_Json = serializer.DeserializeObject(scene_params_json) as Dictionary<string, object>; Dictionary<String, Object> temp_params = (Dictionary<String, Object>)temp_Json; bool overide_aws_userdata = false; if (temp_params.ContainsKey("overide_aws_userdata")) { overide_aws_userdata = (bool)temp_params["overide_aws_userdata"]; } String jsonStr = String.Empty; bool use_cfg_str_from_main = false; if (overide_aws_userdata) use_cfg_str_from_main = true; else { if (!UtilsDLL.AWS_Utils.Get_Launch_Specific_Data(out jsonStr)) { Console.WriteLine("Probably not a AWS machine - could not find userData"); use_cfg_str_from_main = true; } if (String.IsNullOrEmpty(jsonStr)) use_cfg_str_from_main = true; } if (use_cfg_str_from_main) jsonStr = scene_params_json; var jsonObject = serializer.DeserializeObject(jsonStr) as Dictionary<string, object>; params_dict = (Dictionary<String, Object>)jsonObject; }
protected override TimeSpan GetExpiry(string responseText) { var jsonSerializer = new JavaScriptSerializer(); var tokenDictionary = jsonSerializer.DeserializeObject(responseText) as Dictionary<string, object>; return new TimeSpan(0, 0, Convert.ToInt32(tokenDictionary["expires_in"])); }
protected string calculate() { JavaScriptSerializer json_serializer = new JavaScriptSerializer(); Dictionary<string, object> values = (Dictionary<string, object>)json_serializer.DeserializeObject(Request["data"]); OEE oee = new OEE(); try { oee.setFrom(Convert.ToDateTime(values["from"])); oee.setTo(Convert.ToDateTime(values["to"])); oee.partsPerHour = Convert.ToDecimal(values["partsPerHour"]); oee.downtimeMinutes = Convert.ToDecimal(values["downtimeMinutes"]); oee.partsPerHour = Convert.ToDecimal(values["partsPerHour"]); oee.totalPieces = Convert.ToDecimal(values["totalPieces"]); oee.goodUnits = Convert.ToDecimal(values["goodUnits"]); oee.calculateTotal(); } catch { } return ConvertToJsonString(oee); }
private static string GetSwtTokenFromAcs(string serviceNamespace, string clientId, string clientSecret, string scope) { WebClient client = new WebClient(); client.BaseAddress = string.Format(CultureInfo.CurrentCulture, "https://{0}.{1}", serviceNamespace, "accesscontrol.windows.net"); NameValueCollection values = new NameValueCollection(); values.Add("grant_type", "client_credentials"); values.Add("client_id", clientId); values.Add("client_secret", clientSecret); values.Add("scope", scope); byte[] responseBytes = null; try { responseBytes = client.UploadValues("/v2/OAuth2-13", "POST", values); } catch (WebException ex) { throw new InvalidOperationException(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd()); } string response = Encoding.UTF8.GetString(responseBytes); // Parse the JSON response and return the access token var serializer = new JavaScriptSerializer(); Dictionary<string, object> decodedDictionary = serializer.DeserializeObject(response) as Dictionary<string, object>; return decodedDictionary["access_token"] as string; }
public void CrearEmpresa(Empresa empresa) { try { string BASE_URL2 = "http://ws.razonsocialperu.com/rest/PROYUPC/RUC/"; string urlConsulta = string.Format("{0}/{1}", BASE_URL2, empresa.NumeroRuc); var webClient = new WebClient(); var json = webClient.DownloadString(urlConsulta); var js = new JavaScriptSerializer(); var result = js.DeserializeObject(json); Dictionary<string, object> lista = ((object[])(result))[0] as Dictionary<string, object>; var estado = lista.Where(x => x.Key == "status") as Dictionary<string, object>; string value = lista["status"].ToString(); if (value != "EXISTS") throw new WebFaultException<string>("El RUC ingresado no se encuentra registrado en los sistemas tributarios.", HttpStatusCode.NotFound); EmpresaDAO.Crear(empresa); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Created; } catch (Exception ex) { throw ex; } }
/// <summary> /// 翻译 /// </summary> /// <param name="word">需要翻译的词</param> /// <returns></returns> public string GetFanYi(string word) { try { WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。 //百度帐号:y0ngwang,474196974 Byte[] pageData = MyWebClient.DownloadData("http://openapi.baidu.com/public/2.0/bmt/translate?client_id=V6CGLfyaI2ycQBTf8OUf3u0v&q=" + word + "&from=auto&to=auto"); //从指定网站下载数据 var pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句 //{"from":"zh","to":"en","trans_result":[{"src":"\u4f60\u597d","dst":"Hello"}]} pageHtml = pageHtml.Replace("[", ""); pageHtml = pageHtml.Replace("]", ""); JavaScriptSerializer js = new JavaScriptSerializer(); var obj = js.DeserializeObject(pageHtml); string str = "翻译:\n"; Dictionary<string, object> dic = obj as Dictionary<string, object>; str += dic["from"].ToString() + "==>" + dic["to"].ToString() + "\n"; Dictionary<string, object> obbbj = dic.Values.ToArray()[2] as Dictionary<string, object>; str += "原文:\n" + obbbj.Values.ToArray()[0].ToString(); str += "\n译文:\n" + obbbj.Values.ToArray()[1].ToString(); return str; } catch (Exception) { return "你说的话,暂时还不会翻译,翻译使用如【@你好】!"; } }
// GET: MainPage public void Common() { var trips = System.IO.File.ReadAllText(Server.MapPath("~/Scripts/data.json")); JavaScriptSerializer json_serializer = new JavaScriptSerializer(); object data = json_serializer.DeserializeObject(trips); ViewBag.data = data; }
public void GetDirectionsBetweenPostcodes(string postCode1, string postCode2) { var client = new RestClient("http://maps.googleapis.com/maps/api/directions/json"); var request = new RestRequest(Method.GET); request.AddParameter("origin", postCode1); request.AddParameter("destination", postCode2); request.AddParameter("sensor", "false"); var response = client.Execute(request); var content = response.Content; // raw content as string dynamic xx = JsonConvert.DeserializeObject(content); var zz = xx["routes"]; var serializer = new JavaScriptSerializer(); dynamic value = serializer.DeserializeObject(content); var routes = value["routes"]; var oneRoute = routes[0]; //One route var legs = oneRoute["legs"]; var oneLeg = legs[0]; var distance = oneLeg["distance"]; var duration = oneLeg["duration"]; }
public object Deserialize(string input) { if (String.IsNullOrEmpty(input)) return null; JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.DeserializeObject(input); }
private object GetTestGroup(string groupName) { var json = File.ReadAllText(@"tests.json"); var serializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var deserializedObject = serializer.DeserializeObject(json); return ((IDictionary<string, object>)deserializedObject)[groupName]; }
/// <summary> /// 获取AccessToken /// </summary> /// <param name="AppID"></param> /// <param name="AppSecret"></param> /// <returns></returns> public static string GetAccessToken(string AppID, string AppSecret) { JavaScriptSerializer Jss = new JavaScriptSerializer(); string respText = CommonMethod.WebRequestPostOrGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret), ""); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); string accessToken = respDic["access_token"].ToString(); return accessToken; }