简体   繁体   中英

How to convert a Json string to List in c#

In web service i am try to convert a jzonString to a list.

{
    "name": "Test",
    "Fname": "Testing",
    "S1": "Content1",
    "S2": "Content2",
    "S3": "Content3"
}
[WebMethod]
        public int Create(string Detils, string Companyid)
        {
            try
            {

                dynamic ScheduleShift = new JavaScriptSerializer().DeserializeObject(Detils);
                \\ i need to set data to list or to an object

                InvDetails objDetails = new InvDetails();
                List<InvDetails> lstDetails = new List<InvDetails>();

                return objDetails.CreateInvDetails(objDetils);
            }
            catch (Exception ex)
            {
                // Abort Transaction
                throw ex;
            }
        }

Created another library file to declare the object and to insert into db

 public class Inventory
    {
        CommonExecDAL CommonExecDAL = new CommonExecDAL();
        public string name { get; set; }
        public string Fname { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public int intCompanyId { get; set; }


        public int CreateInvComputer(InvDetails objInvDetails)
        {

            SqlParameter[] arParms = new SqlParameter[6];
            .........

        }
    }

If you don't want to create a class :
You can use JObject.Parse() method for deserializing dynamically.

As @SirRufo said, you can deserialize a JSON array into a list. but your JSON string in the sample is a single object!

Anyway, you deserialize JSON string to object with the use JSON.Net .

First, you have a class for Deserialize :

public class Data
{
    public string name { get; set; }
    public string Fname { get; set; }
    public string S1 { get; set; }
    public string S2 { get; set; }
    public string S3 { get; set; }
}

Then you can deserialize JSON string to C# class :

var obj = JsonConvert.DeserializeObject<Data>(jsonString);

Just add reference to System.Web.Extensions ,(built in dll on .NET 4+) :

JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObj =jss.Deserialize<dynamic>(jsonString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM