Json对象序列化与反序列化

时间:2022-10-04 20:47:03

如果后台的参数数对象,需要在前台传入:

JS代码:

//创建JS对象
var CUTTING_TABLET_MO = new Object();
CUTTING_TABLET_MO.CUTTING_TABLET_MO_ID =0;
CUTTING_TABLET_MO.GO_NO = ""; $("#Lab_GO").html();
CUTTING_TABLET_MO.MO_NO = $("#Lab_MO").html();
CUTTING_TABLET_MO.STATUS = "Doing";
CUTTING_TABLET_MO.REMARK = "";
CUTTING_TABLET_MO.CREATE_USER_ID = $("#h_userid").val();
CUTTING_TABLET_MO.CREATE_DATE = new Date().toLocaleString();
CUTTING_TABLET_MO.LAST_MODI_USER_ID = $("#h_userid").val();
CUTTING_TABLET_MO.LAST_MODI_DATE = new Date().toLocaleString();
var CUTTING_TABLET_CUT_LOT = new Object();
CUTTING_TABLET_CUT_LOT.CUTTING_TABLET_CUT_LOT_ID =0;
CUTTING_TABLET_CUT_LOT.CUTTING_TABLET_MO_ID =0;
CUTTING_TABLET_CUT_LOT.CUT_LOT = $("#lbl_CutLotNo").val();
CUTTING_TABLET_CUT_LOT.REMARK = "";
CUTTING_TABLET_CUT_LOT.STATUS = "Doing";
CUTTING_TABLET_CUT_LOT.MARKER_ID = $("#h_MarkerId").val();
CUTTING_TABLET_CUT_LOT.CREATE_USER_ID = $("#h_userid").val();
CUTTING_TABLET_CUT_LOT.CREATE_DATE = new Date().toLocaleString();
CUTTING_TABLET_CUT_LOT.LAST_MODI_USER_ID = $("#h_userid").val();
CUTTING_TABLET_CUT_LOT.LAST_MODI_DATE = new Date().toLocaleString();
//将对象序列化成Json对象
var cuttingTabletObj = JSON.stringify(CUTTING_TABLET_MO);
var cuttingCutLotObj = JSON.stringify(CUTTING_TABLET_CUT_LOT);
//将对象序列化成JSON后传入后台,使用JqueryAjax
publicAjax(ajaxURL + "CuttingTable/MoStateAndCutLotStateUpdate", "{ MoObj: '" + cuttingTabletObj + "', CutObj: '" + cuttingCutLotObj + "' }", function (result) {
});

  Controller.cs 的代码

public void MoStateAndCutLotStateUpdate(string MoObj, string CutObj)
{
//实例化用于序列化的类,using System.Web.Script.Serialization;
JavaScriptSerializer Serializer = new JavaScriptSerializer();
//实例化对象
CUTTING_TABLET_MO cuttingTabletmo = Serializer.Deserialize<CUTTING_TABLET_MO>(MoObj);
CUTTING_TABLET_CUT_LOT cuttingTableCutLot = Serializer.Deserialize<CUTTING_TABLET_CUT_LOT>(CutObj);
//如果是集合使用
            //List<CUTTING_TABLET_MO> cuttingTabletmo = Serializer.Deserialize<list<CUTTING_TABLET_MO>>(MoObj);
}

  -------------------

JS1将对象序列化为json

 function(result){
var json = JSON.stringify(result);//将对象序列化
sessionStorage.setItem("shrinkageData", json);//保存缩略信息,拉布页面扫描需判断
}

JS反序列化为对象

       var json=JSON.parse(sessionStorage.getItem("shrinkageData"));//反序列化
var shrinkageData = json;

c#

using Newtonsoft.Json;

Hashtable hash = new Hashtable();
hash.Add("key1", "val1");
hash.Add("key2", "val2");
hash.Add("key3", "[1,2]");
hash.Add("key4", "[{'k':'v'},{'k1':'v1'}]");
string json = JsonConvert.SerializeObject(hash); php p = new php();
p.age = ;
p.name = "姓名";
string json2 = JsonConvert.SerializeObject(p);//序列化对象
php p2 = JsonConvert.DeserializeObject<php>(json2);//反序列化对象
//js obj: JSON.stringify(points)
"[{},{}]"
List<PointsInfo> p2 = JsonConvert.DeserializeObject<List<PointsInfo>>(obj);
"{}"
Points p2 = JsonConvert..DeserializeObject<Points>(obj);