MVC Newtonsoft.Json解析JSON字符串

前端之家收集整理的这篇文章主要介绍了MVC Newtonsoft.Json解析JSON字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class JsonTestController : Controller
    {
        public ActionResult Index()
        {
            //using Newtonsoft.Json;
            try
            {
                #region 单条数据
                string jsonString = "{\"ID\":1,\"ClassName\":\"name1\",\"Students\":[{\"ID\":1,\"StudentName\":\"StudentName1\",\"ClassID\":0},{\"ID\":2,\"StudentName\":\"StudentName2\",\"ClassID\":0}]}";
                Classes model = (Classes)JsonConvert.DeserializeObject(jsonString,typeof(Classes));
                Classes objModel = JsonConvert.DeserializeObject<Classes>(jsonString);
                List<Student> studentList = model.Students;
                #endregion

                #region 列表数据
                string jsonList = "[{\"ID\":1,\"ClassName\":\"name1\"},\"ClassName\":\"name2\"},{\"ID\":3,\"ClassName\":\"name3\"},{\"ID\":4,\"ClassName\":\"name4\"},{\"ID\":5,\"ClassName\":\"name5\"}]";
                List<Classes> list = (List<Classes>)JsonConvert.DeserializeObject(jsonList,typeof(List<Classes>));
                List<Classes> objList = JsonConvert.DeserializeObject<List<Classes>>(jsonList);

                #endregion
            }
            catch (Exception)
            {
                throw;
            }
            return View();
        }
	}

    public class Classes
    {
        public int ID { get; set; }

        public string ClassName { get; set; }

        public List<Student> Students { get; set; }
    }

    public class Student
    {
        public int ID { get; set; }

        public string StudentName { get; set; }

        public int ClassID { get; set; }
    }
}
原文链接:https://www.f2er.com/json/289663.html

猜你在找的Json相关文章