Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON array(or list) in C#

here is the basic code:

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; }

}

I have tried:

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

and:

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

and neither work. Anyone have any ideas?

like image 314
sadermine Avatar asked Aug 04 '11 02:08

sadermine


1 Answers

This code works for me:

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; }
        }
    }
}
like image 96
Jacob Avatar answered Oct 12 '22 02:10

Jacob