[.net]如何parse剖析json字串, 且不使用json.net, newtonsoft的json套件

  • 83
  • 0

[.net]如何parse剖析json字串, 且不使用json.net, newtonsoft的json套件

newtonsoft公司出的json.net這麼好用為什麼不用呢?
因為公司如果比較舊的專案,大概不會很希望你安裝新的套件上去程式碼專案,怕會有相容性問題,所以下面就來示範如何不用json.net來解析json資料

首先要有json的資料並把他轉成字串(廢話,哈…),如下圖有個table,我們會把他轉換成json的陣列的字串


把table的資料轉成json的字串的話大概會長的像是下面這樣:
[{"StuffType":"02","StuffName":"11","StuffDesc":"22","StuffUnit":"33","StuffQty":"44","Reason":"55","ReturnDate":"2023/09/28","NoReturn":false},{"StuffType":"06","StuffName":"66","StuffDesc":"77","StuffUnit":"88","StuffQty":"99","Reason":"10","ReturnDate":"","NoReturn":true}]


然後用下列的c#程式碼就可以把這個json字串轉換成物件囉:

private class StuffPostModel
{
    public string StuffType { get; set; }
    public string StuffName { get; set; }
    public string StuffDesc { get; set; }
    public int StuffUnit { get; set; }
    public string StuffQty { get; set; }
    public string Reason { get; set; }
    public string ReturnDate { get; set; }
    public bool NoReturn { get; set; }
}

string stuffJson = hidStuffJson.Value;//json 字串
StuffPostModel[] stuffList = new JavaScriptSerializer().Deserialize<StuffPostModel[]>(stuffJson);
 


以上就是本篇的教學

參考資料:
Deserialize json array to c# list object
https://stackoverflow.com/questions/50343016/deserialize-json-array-to-c-sharp-list-object

ps.   如果您的專案剛好也是web類型,而且也剛好是要把畫面上的table資料轉成json的字串,下面的javascript提供給您做為參考,可方便您快速把table資料轉成json的字串:

var tbodyStuff = $('#tbodyStuff');//這是table裡面的tbody
var trs = tbodyStuff.find('tr').not('#trTemplate');//抓出範本tr以外的所有tr(範本tr不會有資料)
console.log(trs.length);
var stuffArr = [];//預計要抓出來的json資料
trs.each(function () {
    var tr = $(this);
    var ddlStuffType = tr.find('select[name*=ddlStuffType]');
    var txtStuffName = tr.find('input[name*=txtStuffName]');
    var txtStuffDesc = tr.find('input[name*=txtStuffDesc]');
    var txtStuffUnit = tr.find('input[name*=txtStuffUnit]');
    var txtStuffQty = tr.find('input[name*=txtStuffQty]');
    var txtReason = tr.find('input[name*=txtReason]');
    var txtReturnDate = tr.find('input[name*=txtReturnDate]');
    var cbNoReturn = tr.find('input[name*=cbNoReturn]');
    //console.log(ddlStuffType.val());
    //console.log(txtStuffName.val());

    var stuffJson = {
        StuffType: ddlStuffType.val(),
        StuffName: txtStuffName.val(),
        StuffDesc: txtStuffDesc.val(),
        StuffUnit: txtStuffUnit.val(),
        StuffQty: txtStuffQty.val(),
        Reason: txtReason.val(),
        ReturnDate: txtReturnDate.val(),
        NoReturn: cbNoReturn.prop('checked'),
    };
    //console.log(JSON.stringify(stuffJson));
    stuffArr.push(stuffJson);
});
    
console.log(JSON.stringify(stuffArr));
var hidStuffJson = $('input[id*=hidStuffJson]');
hidStuffJson.val('');
//json物件轉成字串之後,存放在隱藏欄位
hidStuffJson.val(JSON.stringify(stuffArr));