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


C# Script.Serialization.JavaScriptSerializer.Serialize方法代码示例

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


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

示例1: Codecompletion

        public string Codecompletion(string code, int position, int language, int line, int ch)
        {
            Compression.SetCompression();
            JavaScriptSerializer json = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(code))
                return json.Serialize(new List<string>());

            if (language == (int)LanguagesEnum.CSharp)
            {
                return CsharpComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.Java)
            {
                return JavaComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.CPP || language == (int)LanguagesEnum.CPPClang || language == (int)LanguagesEnum.VCPP)
            {
                return VcppComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.Python)
            {
                return PythonComplete.Complete(code, position, line, ch);
            }
            else
            {
                return json.Serialize(new List<string>());
            }
        }
开发者ID:ren85,项目名称:rextester_win,代码行数:29,代码来源:ServiceController.cs

示例2: ProcessRequest

        /// <summary>
        /// Process Request that updates user info given the HttpContext, and returns confirmation message upon successful completion
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            String jsonString;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                User user = new User
                {
                    FirstName = request.Form["firstName"],
                    LastName = request.Form["lastName"],
                    Gender = request.Form["gender"],
                    PhoneNumber = request.Form["phoneNumber"],
                    Address = request.Form["address"],
                    ZipCode = request.Form["zipCode"],
                    UserName = request.Form["userName"]
                };
                user.UpdateProfile();

                jsonString = serializer.Serialize(new { result = "success" });
            }
            catch (Exception ex)
            {
                jsonString = serializer.Serialize(new { result = ex.Message });
            }
           
            response.Write(jsonString);
            response.ContentType = "application/json";
        }
开发者ID:cs465-crime-busters,项目名称:CrimeBusters,代码行数:34,代码来源:UpdateProfile.ashx.cs

示例3: AcceptGift

        public void AcceptGift(string userId, int sessionId, int playerLevel, string itemId, string senderId, ulong delayInSeconds)
        {
            var serializer = new JavaScriptSerializer();
            var data = new Dictionary<string, object>();
            data.Add("playerLevel", playerLevel);
            data.Add("itemId", itemId);
            data.Add("sender", senderId);
            data.Add("delay", delayInSeconds);

            var rows = new List<Dictionary<string, object>>();

            var item = new Dictionary<string, object>();
            item.Add("data", serializer.Serialize(data));
            item.Add("timeInMillis", this.UnixTime());
            item.Add("playerId", userId);
            item.Add("actionType", 3);
            item.Add("sessionId", sessionId);

            rows.Add(item);

            var fs = new Dictionary<string, object>();
            fs.Add("rows", rows);
            fs.Add("authCode", this.ApiKey);

            this.CurlPostData(serializer.Serialize(fs));
        }
开发者ID:barans,项目名称:ClariticsCSharpSDK,代码行数:26,代码来源:Claritics.cs

示例4: ProcessRequest

        // get : api/Movies?type={current/all order by name etc}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            try
            {
                SetConnectionString();

                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["type"]))
                {
                    throw new ArgumentException("type is not present");
                }

                string type = qpParams["type"].ToString();

                var tableMgr = new TableManager();
                var movies = new List<MovieEntity>();

                if (type.ToLower() == "orderby")
                {
                    movies = tableMgr.GetSortedMoviesByName();
                }
                else if (type.ToLower() == "current")
                {
                    movies = tableMgr.GetCurrentMovies();
                }

                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
               return  json.Serialize(new { Status = "Error", Message = ex.Message });
            }
        }
开发者ID:viren85,项目名称:movie,代码行数:35,代码来源:MoviesController.cs

示例5: ProcessRequest

        // get : api/Actor?n={actor/actress/producer...etc name}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParam = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParam["n"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string actorName = qpParam["n"].ToString();

                // get movies by actor(roles like actor, actress, producer, director... etc)
                var movies = tableMgr.SearchMoviesByActor(actorName);

                // serialize movie list and return
                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES, ActualError = ex.Message });
            }
        }
开发者ID:viren85,项目名称:moviemirchi,代码行数:31,代码来源:ActorController.cs

示例6: OnMessage

        public override void OnMessage(string message)
        {
            var ser = new JavaScriptSerializer();
            var msg = ser.Deserialize<Message>(message);

            switch (msg.Type)
            {
                case MessageType.Join:
                    name = msg.Value.ToString();
                    clientIds.Add(name);
                    var response = ser.Serialize(new
                    {
                        type = MessageType.UpdateClients,
                        value = clientIds.ToArray()
                    });

                    clients.Broadcast(response);
                    break;

                case MessageType.Draw:
                    var responsedata = ser.Serialize(new
                    {
                        type = MessageType.Draw,
                        username = name,
                        value = msg.Value
                    });

                    clients.Broadcast(responsedata);
                    break;

                default:
                    return;
            }
        }
开发者ID:acasquete,项目名称:gang-canvas,代码行数:34,代码来源:CanvasService.svc.cs

示例7: ToJsonModels

        //returns a json string for multiple models
        public string ToJsonModels(IEnumerable<object> models)
        {
            int x = 0;
            int z = models.Count();
            string result = "";
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            foreach (Contact model in models)
            {

                if (x == 0) { result = "["; }

                if (x == z - 1)
                {
                    result += serializer.Serialize(this.ToDictModel(model)).ToString() + "]";
                }
                else
                {
                    result += serializer.Serialize(this.ToDictModel(model)).ToString() + ",";
                }

                x++;

            }

            return result;
        }
开发者ID:hunyoboy,项目名称:contacts_application,代码行数:28,代码来源:Helper.cs

示例8: ajax_SQLExecute

        public String ajax_SQLExecute(String SQL)
        {
            ReturnAjaxData rAjaxResult = new ReturnAjaxData();
            JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 65536 }; //64K
            String r = String.Empty;

            try
            {
                DataTable dt = getSQLConnection().ExecuteData(SQL);
                List<String> ColumnName = new List<String>();
                foreach (DataColumn dc in dt.Columns)
                {
                    ColumnName.Add(dc.ColumnName);
                }

                List<String[]> Rows = new List<String[]>();
                foreach (DataRow dr in dt.Rows)
                {
                    List<String> Cells = new List<String>();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        Cells.Add(dr[i].ToString());
                    }
                    Rows.Add(Cells.ToArray());
                }

                r = js.Serialize(new { Columns = ColumnName.ToArray(), DataItems = Rows.ToArray(), result = true, message = "" });
            }
            catch (Exception ex)
            {
                r = js.Serialize(new { result = false, message = ex.Message });
            }
            return r;
        }
开发者ID:jcingroup,项目名称:C211315_TFTC,代码行数:34,代码来源:XYZController.cs

示例9: ExecuteResult

 /// <summary>
 /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
 /// </summary>
 /// <param name="context">The context within which the result is executed.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
           String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
     {
         throw new InvalidOperationException();
     }
     var response = context.HttpContext.Response;
     if (!String.IsNullOrEmpty(ContentType))
         response.ContentType = ContentType;
     else
         response.ContentType = CallbackApplicationType;
     if (ContentEncoding != null)
         response.ContentEncoding = this.ContentEncoding;
     if (Data != null)
     {
         String buffer;
         var request = context.HttpContext.Request;
         var serializer = new JavaScriptSerializer();
         if (request[JsonpCallbackName] != null)
             buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
         else
             buffer = serializer.Serialize(Data);
         response.Write(buffer);
     }
 }
开发者ID:shadowzcw,项目名称:nCommon,代码行数:35,代码来源:JsonpResult.cs

示例10: ProcessRequest

        /// <summary>
        /// Process request on deletion of user based on HTTP context, returns message upon success
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            String jsonString = String.Empty;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            Models.Login.Login login = new Models.Login.Login(new User
            {
                UserName = request.Form["userName"]
            });

            try
            {
                login.DeleteUser();
                jsonString = serializer.Serialize(new { result = "success" });
            }
            catch (Exception ex)
            {
                jsonString = serializer.Serialize(new { result = ex.Message });
            }
            finally
            {
                response.Write(jsonString);
                response.ContentType = "application/json";
            }
        }
开发者ID:cs465-crime-busters,项目名称:CrimeBusters,代码行数:30,代码来源:DeleteUser.ashx.cs

示例11: GetCoverage

        public string GetCoverage()
        {
            var baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            var path = baseDirectory + "CSVFiles\\CountyFullImmunizationCoverageRate.csv";

            var iop = System.IO.File.ReadAllLines(path).Skip(1).Select(line => new { line, columns = line.Split(','), rows = line.Split(';') }).Select(@t => new
            {
                year1 = @t.columns[1],
                year2 = @t.columns[2],
                year3 = @t.columns[3]
            }).ToList();

            var coverage = new List<List<float>>();

            var coverageYr1 = iop.Select(v => float.Parse(v.year1)).ToList();
            coverage.Add(coverageYr1);
            var coverageYr2 = iop.Select(v => float.Parse(v.year2)).ToList();
            coverage.Add(coverageYr2);
            var coverageYr3 = iop.Select(v => float.Parse(v.year3)).ToList();
            coverage.Add(coverageYr3);
            var jsonSerialiser = new JavaScriptSerializer();
            foreach (var c in coverage)
            {
                var json = jsonSerialiser.Serialize(c);
            }

            var json1 = jsonSerialiser.Serialize(coverage);
            return json1;
        }
开发者ID:njagi13,项目名称:ImmmunizationPerCountyAndMobileWebApi,代码行数:29,代码来源:HomeController.cs

示例12: Diff

        public string Diff(string left, string right)
        {
            int maxLength = 200000;
            Compression.SetCompression();
            JavaScriptSerializer json = new JavaScriptSerializer();

            if (!string.IsNullOrEmpty(left) && left.Length > maxLength)
            {
                return json.Serialize(new JsonData() { IsError = true, Errors = string.Format("Left input is too long (max is {0} characters).\n", maxLength) });
            }

            if (!string.IsNullOrEmpty(right) && right.Length > maxLength)
            {
                return json.Serialize(new JsonData() { IsError = true, Errors = string.Format("Right input is too long (max is {0} characters).\n", maxLength) });
            }

            Service.LinuxService ser = new Service.LinuxService();
            var res = ser.GetDiff(left, right);
            if (res.IsError)
                return json.Serialize(new JsonData() { IsError = true });
            else
            {
                if (!string.IsNullOrEmpty(res.Result))
                {
                    int startIndex = res.Result.IndexOf("<table");
                    if (startIndex != -1)
                        res.Result = res.Result.Substring(startIndex);
                    int endIndex = res.Result.LastIndexOf("</body");
                    if (endIndex != -1)
                        res.Result = res.Result.Substring(0, endIndex);
                }
                return json.Serialize(new JsonData() { Result = res.Result });
            }
        }
开发者ID:ren85,项目名称:rextester_win,代码行数:34,代码来源:DiffController.cs

示例13: GetFacilityAddress_When_CurrentSubscriber_SessionInstance_is_Null

        public void GetFacilityAddress_When_CurrentSubscriber_SessionInstance_is_Null()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                var expectedFacilityAddress = new FacilityAddress();
                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "Subscriber") return null; return null; };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // GetInstance will return the Faked instance
                var myCurrentSubscriber = CurrentSubscriber.GetInstance();

                // Act
                // While we are using a fake, we haven't faked the SessionInstance which
                // means this will be null and this in turn means that
                //GetFacilityAddress should return a new FacilityAddress
                var actualFacilityAddress = myCurrentSubscriber.GetFacilityAddress();

                // Assert
                Assert.IsNotNull(actualFacilityAddress, "CurrentSubscriber.GetInstance().GetFacilityAddress() is null");
                var jss = new JavaScriptSerializer();
                Assert.AreEqual(jss.Serialize(expectedFacilityAddress),jss.Serialize(actualFacilityAddress), "There is a difference between the expected and actual address");
            }
        }
开发者ID:borealwinter,项目名称:simpl,代码行数:33,代码来源:CurrentSubscriberTest.cs

示例14: AddComment

        public string AddComment(string userData)
        {
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            CommentOrder comment = jsonSerializer.Deserialize<CommentOrder>(userData);

            OrdersBusiness orderbusiness = new OrdersBusiness();

            WebService ws = new WebService();
            string result;
            int state;
            if (myHeader != null && ws.VerifyUser(myHeader.UserName, myHeader.Password))
            {
                state = orderbusiness.InsertComment(comment);
                if (state != -1)
                {
                    result = "0"; //增加评论
                }
                else
                {
                    result = "1";
                }
            }
            else
            {
                return jsonSerializer.Serialize("loginfalse");
            }
            return jsonSerializer.Serialize(result);
        }
开发者ID:XingYiJi,项目名称:RunErrands,代码行数:28,代码来源:RunService.asmx.cs

示例15: Main

        public static void Main()
        {
            var digits = new Dictionary<string, int>
            {
                { "one", 1 },
                { "two", 2 },
                { "three", 3 },
                { "four", 4 },
                { "five", 5 },
                { "six", 6 },
                { "seven", 7 },
                { "eight", 8 },
                { "nine", 9 },
            };

            var serializer = new JavaScriptSerializer();
            var digitsInJson = serializer.Serialize(digits);
            Console.WriteLine(digitsInJson);

            var digitsDeserialized = serializer.Deserialize<Dictionary<string, int>>(digitsInJson);
            digitsDeserialized.Print();

            var dict = new Dictionary<int, string>
            {
                { 0, "zero" },
                { 1, "one" },
                { 2, "two" }
            };

            // Exception: On serialization/deserialization of a dictionary, keys must be strings or objects.
            var dictSerialized = serializer.Serialize(dict);
        }
开发者ID:syssboxx,项目名称:Database-Applications,代码行数:32,代码来源:App.cs


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