public ActionResult About(string searchString) { if(searchString=="" || searchString==null) { searchString = "Jurasic Park"; } List<Movie> mo = new List<Movie>(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?name=" + searchString).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput=responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); mo= jsonSerializer.Deserialize<List<Movie>>(jsonInput); return View(mo); }
private void LoadFavorites() { try { string url = string.Format("http://api.mixcloud.com/{0}/favorites/", txtUsername.Text.Trim()); WebRequest wr = WebRequest.Create(url); wr.ContentType = "application/json; charset=utf-8"; Stream stream = wr.GetResponse().GetResponseStream(); if (stream != null) { StreamReader streamReader = new StreamReader(stream); string jsonString = streamReader.ReadToEnd(); var jsonSerializer = new JavaScriptSerializer(); RootObject rootObject = jsonSerializer.Deserialize<RootObject>(jsonString); rptFavorites.DataSource = rootObject.data; rptFavorites.DataBind(); divFavorites.Visible = rootObject.data.Any(); divMessage.Visible = !divFavorites.Visible; } } catch (Exception ex) { } }
public static TestCaseInfo[] GetTestCases(string data) { var serializer = new JavaScriptSerializer(); List<TestCaseInfo> tests = new List<TestCaseInfo>(); foreach (var item in serializer.Deserialize<object[]>(data)) { var dict = item as Dictionary<string, object>; if (dict == null) { continue; } object filename, className, methodName, startLine, startColumn, endLine, kind; if (dict.TryGetValue(Serialize.Filename, out filename) && dict.TryGetValue(Serialize.ClassName, out className) && dict.TryGetValue(Serialize.MethodName, out methodName) && dict.TryGetValue(Serialize.StartLine, out startLine) && dict.TryGetValue(Serialize.StartColumn, out startColumn) && dict.TryGetValue(Serialize.EndLine, out endLine) && dict.TryGetValue(Serialize.Kind, out kind)) { tests.Add( new TestCaseInfo( filename.ToString(), className.ToString(), methodName.ToString(), ToInt(startLine), ToInt(startColumn), ToInt(endLine) ) ); } } return tests.ToArray(); }
public RootObjectOut GetMessageByUser(UserIn jm) { RootObjectOut output = new RootObjectOut(); String jsonString = ""; try { String strConnection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; SqlConnection Connection = new SqlConnection(strConnection); String strSQL = string.Format("SELECT message FROM messages WHERE msgTo = '{0}' AND [msgID] = (SELECT MAX(msgID) FROM messages WHERE msgTo='{1}')", jm.user.ToString(),jm.user.ToString()); SqlCommand Command = new SqlCommand(strSQL, Connection); Connection.Open(); SqlDataReader Dr; Dr = Command.ExecuteReader(); if (Dr.HasRows) { if (Dr.Read()) { jsonString = Dr.GetValue(0).ToString(); } } Dr.Close(); Connection.Close(); } catch (Exception ex) { output.errorMessage = ex.Message; } finally { } JavaScriptSerializer ser = new JavaScriptSerializer(); output = ser.Deserialize<RootObjectOut>(jsonString); return output; }
public void loadVentas() { List<Venta> lv = new List<Venta>(); var javaScriptSerializer = new JavaScriptSerializer(); string jsonVentas = ""; Ventas serv = new Ventas(); serv.Url = new Juddi().getServiceUrl("Ventas"); jsonVentas = serv.getVentas((int)Session["Id"]); lv = javaScriptSerializer.Deserialize<List<Venta>>(jsonVentas); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[7] { new DataColumn("id", typeof(int)), new DataColumn("tipo", typeof(string)), new DataColumn("autor",typeof(string)), new DataColumn("estado",typeof(string)), new DataColumn("fechafin",typeof(string)), new DataColumn("pujamax",typeof(int)), new DataColumn("pujar",typeof(string)) }); for (int i = 0; i < lv.Count; i++) { dt.Rows.Add(lv[i].id, lv[i].tipo, lv[i].autor, lv[i].estado, lv[i].fecha_F, lv[i].precio, "Pujar"); } GridView1.DataSource = dt; GridView1.DataBind(); }
public static List<DeepBlue.Models.Entity.DealClosingCostType> GetDealClosingCostTypesFromDeepBlue(CookieCollection cookies) { // Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc List<DeepBlue.Models.Entity.DealClosingCostType> dealClosingCostTypes = new List<DeepBlue.Models.Entity.DealClosingCostType>(); // Send the request string url = HttpWebRequestUtil.GetUrl("Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc"); HttpWebResponse response = HttpWebRequestUtil.SendRequest(url, null, false, cookies, false, HttpWebRequestUtil.JsonContentType); if (response.StatusCode == System.Net.HttpStatusCode.OK) { using (Stream receiveStream = response.GetResponseStream()) { // Pipes the stream to a higher level stream reader with the required encoding format. using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { string resp = readStream.ReadToEnd(); if (!string.IsNullOrEmpty(resp)) { JavaScriptSerializer js = new JavaScriptSerializer(); FlexigridData flexiGrid = (FlexigridData)js.Deserialize(resp, typeof(FlexigridData)); foreach (Helpers.FlexigridRow row in flexiGrid.rows) { DeepBlue.Models.Entity.DealClosingCostType dealClosingType = new DeepBlue.Models.Entity.DealClosingCostType(); dealClosingType.DealClosingCostTypeID = Convert.ToInt32(row.cell[0]); dealClosingType.Name = Convert.ToString(row.cell[1]); dealClosingCostTypes.Add(dealClosingType); } } else { } response.Close(); readStream.Close(); } } } return dealClosingCostTypes; }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string strResult = Commons.StringHelper.JsonOutString(false, "分类保存失败!"); string action = Commons.WebPage.PageRequest.GetFormString("action"); string str = Commons.WebPage.PageRequest.GetFormString("classifyIds"); JavaScriptSerializer serializer = new JavaScriptSerializer(); List<int> listClassifys = new List<int>(); if (str != "") { listClassifys = serializer.Deserialize<List<int>>(str); } str = Commons.WebPage.PageRequest.GetFormString("productsIds"); List<int> listPros = new List<int>(); if (str != "") { listPros = serializer.Deserialize<List<int>>(str); } if (action.ToLower() == "product") { if (allotProducts(listPros, listClassifys)) { strResult = Commons.StringHelper.JsonOutString(true, "分类保存成功!"); } } else { } context.Response.Write(strResult); }
public static void Main() { var serializer = new JavaScriptSerializer(); var place = Place.GetTestPlace(); var jsonPlace = serializer.Serialize(place); Console.WriteLine("JSON place: "); Console.WriteLine(jsonPlace); Console.WriteLine(); Console.WriteLine("Original place: "); Console.WriteLine(place); Console.WriteLine(); var deserializedPlace = serializer.Deserialize<Place>(jsonPlace); Console.WriteLine("Deserialized place: "); Console.WriteLine(deserializedPlace); // Wrong behavior var deserializedCategory = serializer.Deserialize<Category>(jsonPlace); Console.WriteLine("Deserialized wrong category: "); Console.WriteLine(deserializedCategory); }
public string buscarItem(string dtoChave, string dtoProduto, string dtoEstabelecimento) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno = new DtoRetorno("ACK"); DtoChave chave = js.Deserialize<DtoChave>(dtoChave); DtoProduto produto = js.Deserialize<DtoProduto>(dtoProduto); DtoEnderecoEstabelecimento enderecoEstabelecimento = js.Deserialize<DtoEnderecoEstabelecimento>(dtoEstabelecimento); Chave mChave = new Chave(); try { mChave.validarChave(chave); Item mItem = new Item(); DtoItem item = mItem.abrirItem(produto.id, enderecoEstabelecimento.id); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, item); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoItem com DtoProduto com DtoTipoProduto e DtoFabricante*/ return js.Serialize(retorno); }
public string abrirProduto(string dtoChave, string dtoProduto) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno = new DtoRetorno("ACK"); DtoChave chave = js.Deserialize<DtoChave>(dtoChave); Chave mChave = new Chave(); try { mChave.validarChave(chave); DtoProduto produto = js.Deserialize<DtoProduto>(dtoProduto); Produto mProduto = new Produto(); produto = mProduto.abrirProduto(produto.id); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, produto); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoProduto com DtoTipoProduto e DtoFabricante*/ return js.Serialize(retorno); }
public void ProcessRequest(HttpContext context) { JsonBE jsonObject = new JsonBE(); FirstStep firstStep = new FirstStep(); firstStep.ApplicationQuadri = "IPRI"; firstStep.ITFNumber = "ITF123"; firstStep.DeltaOrFull = "0"; Collection<String> colString = new Collection<String>(); colString.Add("0"); colString.Add("1"); colString.Add("2"); firstStep.Deliverables = colString; firstStep.Environments = colString; jsonObject.Step1 = firstStep; JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); var ser = jsSerializer.Serialize(jsonObject); var test = context.Request.Form[0]; var test2 = jsSerializer.Deserialize<JsonBE>(ser); var test3 = jsSerializer.Deserialize<JsonBE>(test); context.Response.ContentType = "text/plain"; context.Response.Write(ser); }
public void GetApps() { var jss = new JavaScriptSerializer(); string loginJSON = "{user:'******', password:'******'}"; Centrify_API_Interface centLogin = new Centrify_API_Interface().MakeRestCall(CentLoginURL, loginJSON); Dictionary<string, dynamic> loginData = jss.Deserialize<Dictionary<string, dynamic>>(centLogin.returnedResponse); //To pass a specific user name if you log in as an admin. //string appsJSON = "{username:'******'}"; string appsJSON = @"{""force"":""True""}"; Centrify_API_Interface centGetApps = new Centrify_API_Interface().MakeRestCall(CentGetAppsURL, appsJSON, centLogin.returnedCookie); Dictionary<string, dynamic> getAppsData = jss.Deserialize<Dictionary<string, dynamic>>(centGetApps.returnedResponse); var dApps = getAppsData["Result"]["Apps"]; string strAuth = loginData["Result"]["Auth"]; int iCount = 0; foreach (var app in dApps) { string strDisplayName = app["DisplayName"]; string strAppKey = app["AppKey"]; string strIcon = app["Icon"]; AddUrls(strAppKey, strDisplayName, strIcon, iCount, strAuth); iCount++; } }
/*Não Implementado*/ public string adicionarProduto(string dtoChave, string dtoLista, string dtoProdutoDaLista) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno; DtoChave chave = js.Deserialize<DtoChave>(dtoChave); DtoLista lista = js.Deserialize<DtoLista>(dtoLista); Chave mChave = new Chave(); try { mChave.validarChave(chave); DtoProdutoDaLista produtoDaLista = js.Deserialize<DtoProdutoDaLista>(dtoProdutoDaLista); Lista mLista = new Lista(); produtoDaLista = mLista.adicionarProduto(produtoDaLista); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, produtoDaLista); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoProdutoDaLista com o DtoProduto*/ return js.Serialize(retorno); }
public string criarEstabelecimento(string dtoChave, string dtoEnderecoEstabelecimento) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno; DtoChave chave = js.Deserialize<DtoChave>(dtoChave); DtoEnderecoEstabelecimento enderecoEstabelecimento = js.Deserialize<DtoEnderecoEstabelecimento>(dtoEnderecoEstabelecimento); DtoEnderecoEstabelecimento estabelecimento; Chave mChave = new Chave(); try { mChave.validarChave(chave); Estabelecimento mEstabelecimento = new Estabelecimento(); estabelecimento = mEstabelecimento.cadastrarEstabelecimento(enderecoEstabelecimento); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, estabelecimento); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoEnderecoEstabelecimento com DtoEstabelecimento*/ return js.Serialize(retorno); }
public void Reload(XElement element) { JavaScriptSerializer serializer = new JavaScriptSerializer(); BrowserSourceSettings = AbstractSettings.DeepClone(BrowserSettings.Instance.SourceSettings); BrowserInstanceSettings = AbstractSettings.DeepClone(BrowserSettings.Instance.InstanceSettings); String instanceSettingsString = element.GetString("instanceSettings"); String sourceSettingsString = element.GetString("sourceSettings"); if (sourceSettingsString != null && sourceSettingsString.Count() > 0) { try { BrowserSourceSettings = serializer.Deserialize<BrowserSourceSettings>(sourceSettingsString); } catch (ArgumentException e) { API.Instance.Log("Failed to deserialized source settings and forced to recreate; {0}", e.Message); } } if (instanceSettingsString != null && instanceSettingsString.Count() > 0) { BrowserInstanceSettings.MergeWith(serializer.Deserialize<BrowserInstanceSettings>(instanceSettingsString)); } }
/// <summary> /// Parses the access token into an AzureAD token. /// </summary> /// <param name="token"> /// The token as a string. /// </param> /// <returns> /// The claims as an object and null in case of failure. /// </returns> public AzureADClaims ParseAccessToken(string token) { try { // This is the encoded JWT token split into the 3 parts string[] strparts = token.Split('.'); // Decparts has the header and claims section decoded from JWT string jwtHeader, jwtClaims; string jwtb64Header, jwtb64Claims, jwtb64Sig; byte[] jwtSig; if (strparts.Length != 3) { return null; } jwtb64Header = strparts[0]; jwtb64Claims = strparts[1]; jwtb64Sig = strparts[2]; jwtHeader = Base64URLdecode(jwtb64Header); jwtClaims = Base64URLdecode(jwtb64Claims); jwtSig = Base64URLdecodebyte(jwtb64Sig); JavaScriptSerializer s1 = new JavaScriptSerializer(); AzureADClaims claimsAD = s1.Deserialize<AzureADClaims>(jwtClaims); AzureADHeader headerAD = s1.Deserialize<AzureADHeader>(jwtHeader); return claimsAD; } catch (Exception) { return null; } }
public string abrirEstabelecimento(string dtoChave, string dtoEnderecoEstabelecimento) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno; DtoChave chave = js.Deserialize<DtoChave>(dtoChave); DtoEnderecoEstabelecimento enderecoEstabelecimento = js.Deserialize<DtoEnderecoEstabelecimento>(dtoEnderecoEstabelecimento); DtoEnderecoEstabelecimento estabelecimento; Chave mChave = new Chave(); try { mChave.validarChave(chave); Estabelecimento mEstabelecimento = new Estabelecimento(); estabelecimento = mEstabelecimento.abrirEstabelecimento(enderecoEstabelecimento.id); //estabelecimento.itens = mEstabelecimento.procurarProduto(estabelecimento, new DtoProduto()); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, estabelecimento); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoEnderecoEstabelecimento com DtoEstabelecimento e Array de DtoItem com DtoProduto*/ return js.Serialize(retorno); }
private static void FindFollowers(String url) { using (var webClient = new WebClient()) { string html = webClient.DownloadString(url); JavaScriptSerializer ser = new JavaScriptSerializer(); var dict = ser.Deserialize<Dictionary<string, object>>(html); var ids = ((System.Collections.ArrayList)dict["ids"]); foreach (int id in ids) { String screenNameURL = String.Format("https://api.twitter.com/1/users/show.json?user_id={0}&include_entities=true", id); string html2 = webClient.DownloadString(screenNameURL); var dict2 = ser.Deserialize<Dictionary<string, object>>(html2); String screenName = (String) dict2["screen_name"]; Console.WriteLine(id + ": " + screenName); if (_knownNames.Contains(screenName)) continue; String profilPicURL = String.Format("https://api.twitter.com/1/users/profile_image?screen_name={0}&size=original", screenName); MemoryStream ms = new MemoryStream(webClient.DownloadData(profilPicURL)); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); img.Save(_picturesDirectory + "\\" + screenName + ".jpg"); } } }
public string criarLista(string dtoChave, string dtoLista) { JavaScriptSerializer js = new JavaScriptSerializer(); DtoRetorno retorno; DtoChave chave = js.Deserialize<DtoChave>(dtoChave); DtoLista lista = js.Deserialize<DtoLista>(dtoLista); Chave mChave = new Chave(); try { mChave.validarChave(chave); Lista mLista = new Lista(); lista.idUsuario = chave.idUsuario; lista = mLista.criarLista(lista); chave = mChave.atualizarChave(chave); retorno = new DtoRetornoObjeto(chave, lista); } catch (DtoExcecao ex) { retorno = ex.ToDto(); } catch (Exception ex) { retorno = new DtoRetornoErro(ex.Message); } /*Objeto: DtoLista puro*/ return js.Serialize(retorno); }
static void Main(string[] args) { var registeredUsers = new List<Person>(); registeredUsers.Add(new Person() { PersonID = 1, Name = "Bryon Hetrick", Registered = true }); registeredUsers.Add(new Person() { PersonID = 2, Name = "Nicole Wilcox", Registered = true }); registeredUsers.Add(new Person() { PersonID = 3, Name = "Adrian Martinson", Registered = false }); registeredUsers.Add(new Person() { PersonID = 4, Name = "Nora Osborn", Registered = false }); var serializer = new JavaScriptSerializer(); string serializedResult = serializer.Serialize(registeredUsers); File.WriteAllText(@"C:\_test\some.json", serializedResult); string newJson = File.ReadAllText(@"C:\_test\some.json"); List<Person> obj = serializer.Deserialize<List<Person>>(newJson); obj.ForEach(x => System.Console.WriteLine(x.Name)); //////////////////////////////////////////////////////////////// //var ptrn = new Dictionary<string, string[]> // { // { "$1", new string[]{"blah", "blah1" } }, // { "$2", new string[]{"blah", "blah1" } } // }; //var plugin = new Plugin //{ // Prefix = new string[] { "prefix1", "prefix2" }, // Patterns = new Dictionary<string, Dictionary<string, string[]>> // { // {"0", ptrn} // } //}; //serializer = new JavaScriptSerializer(); //string result = serializer.Serialize(plugin); //File.WriteAllText(@"C:\_test\lang.json", result); string ptrns = File.ReadAllText(@"C:\_test\Hebrew.json"); Plugin plug = serializer.Deserialize<Plugin>(ptrns); // Print all prefixes //System.Console.OutputEncoding = System.Text.Encoding.UTF8; foreach (var item in plug.Prefixes) { System.Console.WriteLine(string.Format("Prefix -> {0}", item)); } // Print all patterns from level "0" foreach (var item in plug.Patterns) { System.Console.WriteLine(string.Format("Level: {0}", item.Key)); foreach (var patterns in item.Value) { System.Console.WriteLine(string.Format("\tPattern: {0}", patterns.Key)); foreach (var i in patterns.Value) { System.Console.WriteLine(string.Format("\t\t -> {0}", i)); } } } }
public void DoModifyUser() { string loginJSON = "{user:'******', password:'******'}"; Centrify_API_Interface centLogin = new Centrify_API_Interface().MakeRestCall(CentLoginURL, loginJSON); //A User GUID is needed to modify a user so the user will first need to be queried unless the GUID is hardcoded string strQueryJSON = @"{""Script"":""select * from dsusers where SystemName = '" + UserName + @"';"",""Args"":{""PageNumber"":1,""PageSize"":10000,""Limit"":10000,""SortBy"":"""",""direction"":""False"",""Caching"":-1}}"; Centrify_API_Interface centQueryUser = new Centrify_API_Interface().MakeRestCall(CentQueryURL, strQueryJSON, centLogin.returnedCookie); var jssFindUser = new JavaScriptSerializer(); Dictionary<string, dynamic> centQueryUser_Dict = jssFindUser.Deserialize<Dictionary<string, dynamic>>(centQueryUser.returnedResponse); if (centQueryUser_Dict["success"].ToString() == "True") { Console.WriteLine("User Found:"); ArrayList centFindUser_Results = centQueryUser_Dict["Result"]["Results"]; dynamic centFindUser_Results_Column = centFindUser_Results[0]; Dictionary<string, dynamic> centFindUser_Results_Row = centFindUser_Results_Column["Row"]; strUuid = centFindUser_Results_Row["InternalName"]; } else { Console.WriteLine("Error Running Query: " + centQueryUser_Dict["Message"].ToString()); } if (strUuid != "") { string strModifyUserJSON = @"{""ID"":""" + strUuid + @""", ""enableState"":" + bDisableAccount + @",""state"":""" + strState + @"""}"; Centrify_API_Interface centSetUser = new Centrify_API_Interface().MakeRestCall(CentSetUserURL, strModifyUserJSON); var jss = new JavaScriptSerializer(); Dictionary<string, dynamic> centSetUser_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centSetUser.returnedResponse); if (centSetUser_Dict["success"].ToString() == "True") { if (strNewPass != null) { string strSetPassJSON = @"{""ID"":""" + strUuid + @""",""ConfrimPassword"":""" + strConfirmNewPass + @""",""newPassword"":""" + strNewPass + @"""}"; Centrify_API_Interface centSetPass = new Centrify_API_Interface().MakeRestCall(CentSetPassURL, strSetPassJSON); Dictionary<string, dynamic> centSetPass_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centSetPass.returnedResponse); if (centSetPass_Dict["success"].ToString() == "True") { Console.WriteLine("User Updated."); } else { Console.WriteLine("Failed to Set Password: "******"Failed to Modify user: " + centSetUser.returnedResponse); } } }
static void Main(string[] args) { String token = "ce8c1b87049bf89b62eba1ae87fd9c62"; MoodleUser user = new MoodleUser(); user.username = HttpUtility.UrlEncode("*****@*****.**"); user.password = HttpUtility.UrlEncode("Pass@word1"); user.firstname = HttpUtility.UrlEncode("Daryl"); user.lastname = HttpUtility.UrlEncode("Orwin"); user.email = HttpUtility.UrlEncode("*****@*****.**"); List<MoodleUser> userList = new List<MoodleUser>(); userList.Add(user); Array arrUsers = userList.ToArray(); String postData = String.Format("users[0][username]={0}&users[0][password]={1}&users[0][firstname]={2}&users[0][lastname]={3}&users[0][email]={4}", user.username, user.password, user.firstname, user.lastname, user.email); string createRequest = string.Format("http://MyMoodleUrl.com/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsrestformat=json", token, "core_user_create_users"); // Call Moodle REST Service HttpWebRequest req = (HttpWebRequest)WebRequest.Create(createRequest); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; // Encode the parameters as form data: byte[] formData = UTF8Encoding.UTF8.GetBytes(postData); req.ContentLength = formData.Length; // Write out the form Data to the request: using (Stream post = req.GetRequestStream()) { post.Write(formData, 0, formData.Length); } // Get the Response HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream resStream = resp.GetResponseStream(); StreamReader reader = new StreamReader(resStream); string contents = reader.ReadToEnd(); // Deserialize JavaScriptSerializer serializer = new JavaScriptSerializer(); if (contents.Contains("exception")) { // Error MoodleException moodleError = serializer.Deserialize<MoodleException>(contents); } else { // Good List<MoodleCreateUserResponse> newUsers = serializer.Deserialize<List<MoodleCreateUserResponse>>(contents); } }
/// <summary> /// The .NET Framework offers the JavaScriptSerializer that you can use to deserialize a JSON string into an object. /// You can find the JavaScriptSerializer in the System.Web.Extensions /// dynamic-link library (DLL) in the System.Web.Script.Serialization namespace. /// </summary> /// <param name="input"></param> public static void DeserializeJson(string input) { var serializer = new JavaScriptSerializer(); var result = serializer.Deserialize<Dictionary<string, object>>(input); // In this case, you are deserializing the data to a Dictionary<string,object>. // You can then loop through the dictionary to see the property names and their values. // Its also possible to match to an type var personResult = serializer.Deserialize<Person>(input); }
static int Main (string [] args) { JsonObject obj = new JsonObject (); string json; #if !MONO MemoryStream ms = new MemoryStream (); DataContractJsonSerializer dcSerializer = new DataContractJsonSerializer (typeof (JsonObject)); dcSerializer.WriteObject (ms, obj); ms.Position = 0; StreamReader sr = new StreamReader (ms); json = sr.ReadToEnd (); Assert.AreEqual ("{\"int_key\":null}", json, "#1"); ms = new MemoryStream (); StreamWriter sw = new StreamWriter (ms); sw.Write (json); sw.Flush (); ms.Position = 0; obj = (JsonObject) dcSerializer.ReadObject (ms); Assert.IsNull (obj.int_key, "#2"); #endif json = "{\"int_key\":null}"; JavaScriptSerializer jsSerializer = new JavaScriptSerializer (); obj = jsSerializer.Deserialize<JsonObject> (json); Assert.IsNull (obj.int_key, "#3"); json = "{\"int_key\" : \"\"}"; #if !MONO ms = new MemoryStream (); sw = new StreamWriter (ms); sw.Write (json); sw.Flush (); ms.Position = 0; try { obj = (JsonObject) dcSerializer.ReadObject (ms); Assert.Fail ("#4"); } catch (SerializationException) { } #endif obj = jsSerializer.Deserialize<JsonObject> (json); Assert.IsNull (obj.int_key, "#5"); return 0; }
public ActionResult Conversar(string search) { Usuario user = (Usuario)Session["user"]; var service = new WebService.WebServiceSoapClient(); JavaScriptSerializer js=new JavaScriptSerializer(); var conv = js.Deserialize<Conversaciones>(service.conv_verificarConversacion(user.username, search)); if (conv.conv_id == 0) { service.conv_crearConversacion(user.username, search,""); } js.Deserialize<Conversaciones>(service.conv_verificarConversacion(user.username, search)); return RedirectToAction("Cargar?conv_id="+conv.conv_id, "Conversaciones"); }
protected override void BeginProcessing() { ProgressRecord pr = new ProgressRecord(1, "Create Custom Module", string.Format("Upload custom module ZIP file \"{0}\" into Azure ML Studio", CustomModuleZipFileName)); pr.PercentComplete = 1; pr.CurrentOperation = "Uploading custom module ZIP file..."; WriteProgress(pr); string uploadedResourceMetadata = Sdk.UploadResource(GetWorkspaceSetting(), "Zip"); JavaScriptSerializer jss = new JavaScriptSerializer(); dynamic m = jss.Deserialize<object>(uploadedResourceMetadata); string uploadId = m["Id"]; Task<string> task = Sdk.UploadResourceInChunksAsnyc(GetWorkspaceSetting(), 1, 0, uploadId, CustomModuleZipFileName, "Zip"); while (!task.IsCompleted) { if (pr.PercentComplete < 100) pr.PercentComplete++; else pr.PercentComplete = 1; Thread.Sleep(500); WriteProgress(pr); } string uploadMetadata = task.Result; string activityId = Sdk.BeginParseCustomModuleJob(GetWorkspaceSetting(), uploadMetadata); pr.CurrentOperation = "Creating custom module..."; WriteProgress(pr); dynamic statusObj = jss.Deserialize<object>(Sdk.GetCustomModuleBuildJobStatus(GetWorkspaceSetting(), activityId)); string jobStatus = statusObj[0]; while (jobStatus == "Pending") { if (pr.PercentComplete < 100) pr.PercentComplete++; else pr.PercentComplete = 1; statusObj = jss.Deserialize<object>(Sdk.GetCustomModuleBuildJobStatus(GetWorkspaceSetting(), activityId)); jobStatus = statusObj[0].ToString(); Thread.Sleep(500); WriteProgress(pr); } pr.PercentComplete = 100; WriteProgress(pr); if (jobStatus == "Finished") { string moduleId = statusObj[1]; WriteObject(moduleId); } else throw new System.Exception("Custom module upload failed: " + statusObj[1]); }
/// <summary> /// 获取微信分组(这里会存到缓存,缓存过期后才去微信服务器获取) /// </summary> /// <returns></returns> public static List<UserGroup> GetGroups() { try { List<UserGroup> resultList = new List<UserGroup>(); object obj = MemoryCacheHelper.GetExistsCache<List<UserGroup>>(groupCacheName); if (obj == null) //未找到缓存 ,则获取 { string result = HttpHelper.GetHtml(CommonData.GetGroupListUrl); JavaScriptSerializer js = new JavaScriptSerializer(); SortedDictionary<string, object> sdResult = js.Deserialize<SortedDictionary<string, object>>(result); if (sdResult != null) { if (sdResult.ContainsKey("errcode")) //有错误 { throw new ApplicationException(sdResult.ContainsKey("errcode") ? "获取分组发生错误;代码为:" + sdResult["errcode"] + (sdResult.ContainsKey("errmsg") ? ";错误描述为:" + sdResult["errmsg"] : "") : ""); } SortedDictionary<string, List<UserGroup>> objList = js.Deserialize<SortedDictionary<string, List<UserGroup>>>(result); if (objList.ContainsKey("groups")) { resultList = objList["groups"]; } } else { throw new ApplicationException("获取分组返回的格式错误"); } if (resultList != null && resultList.Count > 0) MemoryCacheHelper.AddCache<List<UserGroup>>(groupCacheName, resultList, ts); } else { resultList = (List<UserGroup>) obj; } return resultList; } catch (Exception ex) { LogHelper.WriteError("获取分组错误!错误信息为:" + ex.Message); return new List<UserGroup>(); } }
public ActionResult DetailMovie(string movieId,string youTubeId) { if (youTubeId == "" || youTubeId == null) { youTubeId = ""; } DetailMovie movie = new Models.DetailMovie(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?IMDBid=" + movieId + "&YouTubeid=" + youTubeId).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput = responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); movie = jsonSerializer.Deserialize<DetailMovie>(jsonInput); return View(movie); }
public static Dictionary<string, object> CreateProject(string Key, string Name) { try { string url = GetRegistryValue(Params.CEPTAH_CONN_REG_KEY, "JiraUrl"); string user = ReadDocumentProperties(Params.USER_NAME_PROP); Microsoft.Office.Core.DocumentProperty p = (Microsoft.Office.Core.DocumentProperty)Globals.ThisAddIn.Application.ActiveProject.BuiltinDocumentProperties["Manager"]; string pass = TempPass; string urlParameters = "projectname=" + HttpUtility.UrlEncode(Name.Replace(".mpp", "")) + "&projectkey=" + Key.ToUpper() + "&projectlead=" + user; //+ "&projectdesc=" + HttpUtility.UrlEncode("Описание проекта"); string FinishURL = url + "/rest/scriptrunner/latest/custom/createProject1?" + urlParameters; WebRequest request = WebRequest.Create(FinishURL); string upass = Base64Encode(user + ":" + pass); request.Headers.Add("Authorization", "Basic " + upass); request.ContentType = "application/json"; WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s); JavaScriptSerializer ser = new JavaScriptSerializer(); return ser.Deserialize<Dictionary<string, object>>(sr.ReadToEnd()); //MessageBox.Show(json); } catch (Exception ex) { MessageBox.Show(ex.Message + " " + ex.StackTrace); return null; } }
public static string GetValidate(string _ModuleName, string _A, string _B, string _C, string _D) { string Result = ""; try { System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers string arr = client.DownloadString(string.Format("{0}api/Validate/{1}?&_A={2}?&_B={3}?&_C={4}?&_D={5}", System.Web.HttpContext.Current.Session["WebApiUrl"].ToString(), _ModuleName, _A, _B, _C, _D)); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); Result = serializer.Deserialize<string>(arr); //using (var client = new HttpClient()) //{ // client.BaseAddress = new Uri(System.Web.HttpContext.Current.Session["WebApiUrl"].ToString()); // client.DefaultRequestHeaders.Accept.Clear(); // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // var response = client.GetAsync(string.Format("api/Validate/{0}?&_A={1}?&_B={2}?&_C={3}?&_D={4}", _ModuleName, _A, _B, _C, _D)) ; //} } catch (Exception) { Result = "#Error"; } return Result; }