客户端:
字符串转为对象:$.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中,会自动转,但仅限简单对象。