C#中,JSON字符串轉換成對象。


在前台提交(post)的數據中。除了強類型的數據外,還有一個額外的json數據提交

在這里我的辦法是,在前台把json對象轉換成字符串,然后提交。

測試demo

前台:

    @using(Html.BeginForm())
    {
        <input type="text" id="json" name="json"/>
        <input type="submit" value="提交"/>
    }

<script>
    var json = [{ "Name": "小馬寶莉", "ID": 9, "Stock": "abc" }];
    json.push({ "Name": "海綿寶寶", "ID": 8, "Stock": "xyz" })
    var jsonstr = JSON.stringify(json);

    $('#json').val(jsonstr);
    //alert(jsonstr);
</script>

  后台:

       [HttpPost]
        public ActionResult AjaxPager(string json)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            //JsonClass jsonClass = (JsonClass)js.Deserialize(json, typeof(JsonClass)); ;
            //var test = js.Deserialize(json, typeof(JsonClass));
            
            // 如果是一維數組的json用這個
            // JsonClass jc = js.Deserialize<JsonClass>(json);


            // 把多維數組轉換成List泛型。
            List<JsonClass> jc = js.Deserialize<List<JsonClass>>(json);

            return View();
        }
    }
    public class JsonClass
    {
        public string Name { get; set; }
        public int ID { get; set; }
        public string Stock { get; set; }
    }

  這樣就可以方便處理了。

記錄一下。備用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM