当前位置: 首页>>代码示例>>C#>>正文


C# JavaScriptSerializer.DeserializeObject方法代码示例

本文整理汇总了C#中JavaScriptSerializer.DeserializeObject方法的典型用法代码示例。如果您正苦于以下问题:C# JavaScriptSerializer.DeserializeObject方法的具体用法?C# JavaScriptSerializer.DeserializeObject怎么用?C# JavaScriptSerializer.DeserializeObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在JavaScriptSerializer的用法示例。


在下文中一共展示了JavaScriptSerializer.DeserializeObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: setLocation

 // public static Dictionary<string, Dictionary<string, string>> userLocation=new Dictionary<string,Dictionary<string,string>>();
 /// <summary>
 /// 设置自动上发的地址
 /// ygh 2014/3/12
 /// </summary>
 /// <param name="openid"></param>
 /// <param name="location"></param>
 public static void setLocation(string openid,string location)
 {
     JavaScriptSerializer a = new JavaScriptSerializer();
     Dictionary<string, object> o = (Dictionary<string, object>)a.DeserializeObject(location);
     WEC_WZ_LOCATION userLocation = new WEC_WZ_LOCATION();
     userLocation.OPENID = openid;
     userLocation.LATITUDE=(string)o["Latitude"];
     userLocation.LONGITUDE=(string)o["Longitude"];
     userLocation.PRECISION=(string)o["Precision"];
     userLocation.ADDTIME = DateTime.Now;
     BLLTable<WEC_WZ_LOCATION>.Insert(userLocation,WEC_WZ_LOCATION.Attribute.ID);
 }
开发者ID:Fred-Lee,项目名称:AppInOneBPM,代码行数:19,代码来源:LocationUtil.cs

示例2: getAccessToken

    /// <summary>
    /// 传入appid和secret获取accesstoken
    /// </summary>
    /// <param name="appid"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public static string getAccessToken(string appid,string secret)
    {
        string param = "";
        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        StreamWriter sw = new StreamWriter(@"c:\e.txt");
        sw.Write(""+url);
        sw.Close();
        string content=httpForm(param,url,"GET");

        JavaScriptSerializer a = new JavaScriptSerializer();
        Dictionary<string, object> o = (Dictionary<string, object>)a.DeserializeObject(content);
        string access_token = (string)o["access_token"];
        return access_token;
    }
开发者ID:Fred-Lee,项目名称:AppInOneBPM,代码行数:20,代码来源:HttpUtil.cs

示例3: Main

    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
开发者ID:travis1230,项目名称:RosettaCodeData,代码行数:16,代码来源:json.cs

示例4: Deserialize

		private static ValueDictionary Deserialize (string input)
		{
			try
			{
				ValueDictionary data = new ValueDictionary ();
				
				JavaScriptSerializer serializer = new JavaScriptSerializer ();
				object value = serializer.DeserializeObject (input);

				AppendBindingData (data, String.Empty, value);
				return data;
			}
			catch
			{
				return null;
			}
		}
开发者ID:radischevo,项目名称:Radischevo.Wahha,代码行数:17,代码来源:JsonValueProviderFactory.cs

示例5: Routes

        public Routes()
        {
            WebSocket["/smschat"] = _ => new WebSocketSmsChatHandler();

              Post["/{userId}/callback", true] = async (c, t) =>
              {
            var userId = (string)c.UserId;
            Debug.Print("Handling Catapult callback for user Id {0}", userId);
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
              var json = await reader.ReadToEndAsync();
              Debug.Print("Data from Catapult for {0}: {1}", userId, json);
              var serializer = new JavaScriptSerializer();
              var data = serializer.DeserializeObject(json);
              WebSocketHandler[] sockets;
              lock (WebSocketSmsChatHandler.ActiveSockets)
              {
            sockets = WebSocketSmsChatHandler.ActiveSockets.ToArray();
              }
              foreach (var socket in sockets.Where(s => (string) s.WebSocketContext.Items["userId"] == userId))
              {
            Debug.Print("Sending Catapult data to websocket client");
            socket.EmitEvent("message", data);
              }
              return "";
            }
              };

              Post["/upload", true] = async (c, t) =>
              {
            Debug.Print("Uploading file");
            var file = Request.Files.First();
            var fileName = Guid.NewGuid().ToString("N");
            var serializer = new JavaScriptSerializer();
            var auth = serializer.Deserialize<Dictionary<string, string>>(Request.Headers.Authorization);
            var client = Client.GetInstance(auth["UserId"], auth["ApiToken"], auth["ApiSecret"]);
            await Media.Upload(client, fileName, file.Value, file.ContentType);
            return new Dictionary<string, string>
            {
              {"fileName", fileName}
            };
              };
        }
开发者ID:BandwidthExamples,项目名称:csharp-web-sms-chat,代码行数:43,代码来源:Routes.cs

示例6: ProcessRequest

    public void ProcessRequest(HttpContext context)
    {
        try {
            var Request = context.Request;
            var Response = context.Response;
            log.Write( LogEvent.Info, "Processing request: {0}", Request.Url.ToString() );

            string providerName = Request["provider"];
            string operationName = Request["operation"];
            string contextJson = Request["context"];
            string langCode = Request["language"];
            try {
                if (!String.IsNullOrEmpty(langCode))
                    Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(langCode);
            } catch {
                log.Write( LogEvent.Warn, "Cannot apply language settings (language: {0}, request: {1})", langCode, Request.Url.ToString() );
            }

            var json = new JavaScriptSerializer();
            var prvContext = contextJson!=null ? json.DeserializeObject(contextJson) : null;

            if (providerName!=null) {
                var provider = WebManager.GetService<IProvider<object,object>>(providerName);
                if (provider!=null) {
                    var result = provider.Provide(prvContext);
                    if (result!=null)
                        Response.Write( json.Serialize(result) );
                }
            } else if (operationName!=null) {
                // maybe operation?
                var op = WebManager.GetService<IOperation<object>>(operationName);
                if (op!=null) {
                    op.Execute(prvContext);
                }
            }
        } catch (Exception ex) {
            log.Write(LogEvent.Warn, String.Format("exception={0}, url={1}", ex, context.Request.Url) );

            context.Response.Write(ex.Message);
            context.Response.StatusCode = 510; /*custom code:ajax error*/
        }
    }
开发者ID:Mariamfelicia,项目名称:nreco,代码行数:42,代码来源:ProviderAjaxHandler.cs

示例7: GetTransformData

    /// <summary>
    /// 将json数据转换为定义好的对象,数据转换为DataTable
    /// </summary>
    /// <param name="jsonText"></param>
    /// <returns></returns>
    public static GeneralSearchResult GetTransformData(string jsonText)
    {
        GeneralSearchResult gsr = new GeneralSearchResult();
        JavaScriptSerializer s = new JavaScriptSerializer();

        object[] rows = (object[])s.DeserializeObject(jsonText);
        Dictionary<string, object> dicFieldDefine = (Dictionary<string, object>)rows[0];
        foreach (KeyValuePair<string, object> ss in dicFieldDefine)
        {
            gsr.FieldDefine.Columns.Add(ss.Key, typeof(string));
        }
        gsr.RetrunData = gsr.FieldDefine.Clone();
        foreach (object ob in rows)
        {
            Dictionary<string, object> val = (Dictionary<string, object>)ob;
            DataRow dr = gsr.RetrunData.NewRow();
            foreach (KeyValuePair<string, object> sss in val)
            {
                dr[sss.Key] = sss.Value;
            }
            gsr.RetrunData.Rows.Add(dr);
        }
        return gsr;
    }
开发者ID:san90279,项目名称:UK_OAS,代码行数:29,代码来源:JsonHelper.cs

示例8: GeneratePersonalData

        public PersonalDataStructure GeneratePersonalData(UserGenderEnum? gender = null)
        {
            string contactDataUrl = "http://api.randomuser.me/0.4/";

            if (gender != null)
            {
                contactDataUrl = URLHelper.AddParameterToUrl(contactDataUrl, "gender", gender.Value == UserGenderEnum.Female ? "female" : "male");
            }

            var serializer = new JavaScriptSerializer();
            string jsonResponse = new WebClient().DownloadString(contactDataUrl);

            dynamic response = serializer.DeserializeObject(jsonResponse);
            dynamic user = response["results"][0]["user"];

            var capitalizer = new FirstLetterCapitalizer();

            var personalData = new PersonalDataStructure
            {
                Gender = user["gender"] == "male" ? UserGenderEnum.Male : UserGenderEnum.Female,
                FirstName = capitalizer.CapitalizeFirstLetters((string)user["name"]["first"]),
                LastName = capitalizer.CapitalizeFirstLetters((string)user["name"]["last"]),
                Address = capitalizer.CapitalizeFirstLetters((string)user["location"]["street"]),
                City = capitalizer.CapitalizeFirstLetters((string)user["location"]["city"]),
                MobilePhone = user["cell"],
                HomePhone = user["phone"],
                ZIP = user["location"]["zip"],
            };

            personalData.Email = personalData.FirstName + "." + personalData.LastName + "@" + StaticRandomCompanies.NextCompanyName() + ".com";

            return personalData;
        }
开发者ID:arvind-web-developer,项目名称:csharp-projects-Jemena-Kentico-CMS,代码行数:33,代码来源:Generator.aspx.cs

示例9: GetControlSelectedIds

 protected override IEnumerable GetControlSelectedIds()
 {
     var json = new JavaScriptSerializer();
     var selectedList = json.DeserializeObject(selectedValues.Value ) as IEnumerable;
     var res = new ArrayList();
     foreach (IDictionary<string,object> i in selectedList)
         res.Add( i[ValueFieldName] );
     return res.ToArray();
 }
开发者ID:Mariamfelicia,项目名称:nreco,代码行数:9,代码来源:McDropDownRelationEditor.ascx.cs

示例10: GetControlSelectedIds

 protected override IEnumerable GetControlSelectedIds()
 {
     var json = new JavaScriptSerializer();
     var selectedList = json.DeserializeObject(selectedValues.Value ) as IEnumerable;
     var res = new ArrayList();
     foreach (string fileName in selectedList)
         res.Add( fileName );
     return res.ToArray();
 }
开发者ID:Mariamfelicia,项目名称:nreco,代码行数:9,代码来源:VfsFileRelationEditor.ascx.cs

示例11: GetQrCodeTicketTemp

    public static string GetQrCodeTicketTemp(string token, long scene)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token);
        req.Method = "post";
        req.ContentType = "raw";
        //Stream streamReq = req.GetRequestStream();
        StreamWriter sw = new StreamWriter(req.GetRequestStream());
        sw.Write("{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\":" + scene.ToString().PadLeft(32,'0') + "}}}");
        sw.Close();
        sw = null;

        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        Stream s = res.GetResponseStream();
        StreamReader sr = new StreamReader(s);
        string strTicketJson = sr.ReadToEnd();
        sr.Close();
        s.Close();
        sr = null;
        s = null;
        res.Close();
        res = null;
        req.Abort();
        req = null;

        try
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(strTicketJson);
            object v;
            json.TryGetValue("ticket", out v);
            token = v.ToString();
            return token;
        }
        catch
        {

            return strTicketJson;
        }
    }
开发者ID:cangjie,项目名称:lq_yeepay,代码行数:39,代码来源:Util.cs

示例12: FromJson

 public virtual void FromJson(string json)
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     IDictionary<string, object> dictionary = jss.DeserializeObject(json) as IDictionary<string, object>;
     FromJsonDictionary(dictionary);
 }
开发者ID:Esri,项目名称:arcgis-viewer-silverlight,代码行数:6,代码来源:ParameterConfig.cs

示例13: jsonToDict

    /*********************************************************************/
    /* JSON */
    /*********************************************************************/
#if USE_JSON
    /*
     * [Function]
     * convert json string into dictionary object
     * [Input]
     * json string
     * [Output]
     * object, internally is dictionary
     * [Note]
     * 1.you should know the internal structure of the dictionary
     * then converted to specific type of yours
     */
    public Object jsonToDict(string jsonStr)
    {
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
        Object dictObj = jsonSerializer.DeserializeObject(jsonStr);

        return dictObj;
    }
开发者ID:caozq19,项目名称:crifanLib,代码行数:22,代码来源:crifanLib.cs

示例14: DeserializeDictionary

 public static IDictionary<int, string> DeserializeDictionary(string serialized)
 {
     if (string.IsNullOrEmpty(serialized))
         return null;
     JavaScriptSerializer jss = new JavaScriptSerializer();
     IDictionary<string, object> dictionary = jss.DeserializeObject(serialized) as IDictionary<string, object>;
     Dictionary<int, string> dict = new Dictionary<int, string>();
     foreach (var item in dictionary)
     {
         int id;
         if (int.TryParse(item.Key, out id))
         {
             dict.Add(id, item.Value as string);
         }
     }
     return dict;
 }
开发者ID:konglingjie,项目名称:arcgis-viewer-silverlight,代码行数:17,代码来源:LayerExtensions.cs

示例15: WeatherInfo

    /// <summary>
    /// 7天天气预报
    /// </summary>
    /// <param name="futureday">未来天数0-6</param>
    /// <returns></returns>
    public static Dictionary<string, object> WeatherInfo(int futureday)
    {
        Dictionary<string, object> val = new Dictionary<string, object>();
        if (futureday>6)
        {
            val.Add("weaid", "未知");
            val.Add("days", DateTime.Now.Date.AddDays(futureday).ToString("yyyy-MM-dd"));
            val.Add("week", TimeHelper.GetFormatWeek1(DateTime.Now.Date.AddDays(futureday)));
            val.Add("cityno", "未知");
            val.Add("citynm", "未知");
            val.Add("cityid", "未知");
            val.Add("temperature", "未知");
            val.Add("humidity", "未知");
            val.Add("weather", "未知");
            val.Add("weather_icon", "Images/Weather/d/0.png");
            val.Add("weather_icon1", "Images/Weather/n/0.png");
            val.Add("wind", "未知");
            val.Add("winp", "未知");
            val.Add("temp_high", "?");
            val.Add("temp_low", "?");
            val.Add("humi_high", "?");
            val.Add("humi_low", "?");
            val.Add("weatid", "0");
            val.Add("weatid1", "0");
            val.Add("windid", "0");
            val.Add("winpid", "0");
        }
        else
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~/WeatherJson.txt");
            string jsonData = File.ReadAllText(path, Encoding.Default);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(jsonData);
            object[] result = (object[])json["result"];
            val = (Dictionary<string, object>)result[futureday];
        }
        return val;
    }
开发者ID:weikety,项目名称:WeatherHelper,代码行数:44,代码来源:WeatherHelper.cs


注:本文中的JavaScriptSerializer.DeserializeObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。