小编典典

在C#中反序列化JSON数组(或列表)

ajax

这是基本代码:

public static string DeserializeNames()
{

    jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

    JavaScriptSerializer ser = new JavaScriptSerializer();

    nameList myNames = ser.Deserialize<nameList>(jsonData);

    return ser.Serialize(myNames);
}

//Class descriptions

public class name
{

   public string last { get; set; }

}

public class nameList
{

   public List<name> { get; set; }

}

我努力了:

nameList myNames = ser.Deserialize<nameList>(jsonData);

和:

List<name> myNames = ser.Deserialize<List<name>>(jsonData);

而且都不起作用。有人有主意吗?


阅读 961

收藏
2020-07-26

共1个答案

小编典典

该代码对我有用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Json
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DeserializeNames());
            Console.ReadLine();
        }

        public static string DeserializeNames()
        {
            var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

            JavaScriptSerializer ser = new JavaScriptSerializer();

            nameList myNames = ser.Deserialize<nameList>(jsonData);

            return ser.Serialize(myNames);
        }

        //Class descriptions

        public class name
        {
            public string last { get; set; }
        }

        public class nameList
        {
            public List<name> name { get; set; }
        }
    }
}
2020-07-26