zoukankan      html  css  js  c++  java
  • 客户端、服务器端中JSON字符串与对象的转换

    客户端:

    字符串转为对象:$.parseJSON(json);

    对象转为字符串:JSON.stringify(_pasteDataItem)

    服务器端(c#):

    对象:

     [DataContract(Namespace = "")]         public class SecurityRequest //: ServiceRequestBase         {             /// <summary>             /// Ctor - allocate the list             /// </summary>             public SecurityRequest()             {             }

                [DataMember]             public string RoleName { get; set; }

                [DataMember]             public string UserAccount { get; set; }

                [DataMember]             public bool IsMarkedForDelete { get; set; }

                [DataMember]             public bool IsOld { get; set; }         }

    对象转为字符串:

    PayloadBuilder.WriteObjToJson(userList);


        public static class PayloadBuilder
        {
            public static string WriteObjToJson(Object obj)
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(obj.GetType());
                string jsString = "";
                using (MemoryStream stream = new MemoryStream())
                {
                    js.WriteObject(stream, obj);
                    jsString = Encoding.UTF8.GetString(stream.ToArray());
                }
                return jsString;
            }
        }

    字符串转为对象:
                var secList = (List<SecurityRequest>)DeserializeJsonString(security, typeof(List<SecurityRequest>));
            public static Object DeserializeJsonString(string jsonString, Type type)
            {
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
                {
                    DataContractJsonSerializer js = new DataContractJsonSerializer(type);
                    return js.ReadObject(ms);
                }
            }

     如是MVC中,会自动转,但仅限简单对象。

  • 相关阅读:
    控件的用法ComboBox;RadionButton;Timer;DataGridView
    echo.js实现图片延迟加载,
    取消移动端a标签点击变色
    JS实现上传图片实时预览
    Myeclipse6.0安装svn插件
    警告: Parameters: Character decoding failed. Parameter skipped
    jsp到action 传递url时中文出现乱码
    java面试题
    myeclipse中hibernate出错
    java中abstract的用法
  • 原文地址:https://www.cnblogs.com/qianblue/p/3228259.html
Copyright © 2011-2022 走看看