简体   繁体   中英

Convert an List<object>to user defined class

I have some data that is object IEnumerable, how to do I convert it into class type, the name of class is option

    "option": {
  "id": 8204,
  "name": "250 ML",
  "price": 40.0,
  "status": 1,
  "archive": 0
}

   "option": {
  "id": 8204,
  "name": "250 ML",
  "price": 40.0,
  "status": 1,
  "archive": 0
}
class Option
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public long Price { get; set; }
        public long Status { get; set; }
        public long Archive { get; set; }
    }

so far tried =>

foreach (var VARIABLE_3 in (IEnumerable) VARIABLE_2)
                        {
                            if ( VARIABLE_3.ToString().Contains("option") && !VARIABLE_3.ToString().Contains("options"))
                            {
                                object[] values = ((IEnumerable)VARIABLE_3).Cast<object>().ToArray();
                                //Option[] values = VARIABLE_3.ToString().Cast<Option>().ToArray();
                                foreach (var VARIABLE in values)
                                {
                                    strStringBuilder.Append("VARIABLE: " + VARIABLE + "\n");
                                }
                            }
                        }

Use JavascriptSerializer or Json.Net serializer to serialize or deserialize Json string.

string jsonArrayObject = @"
[
  {     "id": 8204,
        "name": "250 ML",
        "price": 40.0,
        "status": 1,
        "archive": 0
  },
  {
         "id": 8208,
        "name": "Coke",
        "price": 0.0,
        "status": 1,
         "archive": 0
  }
]";

Javascript Serializer

List<Option> optionList = new System.Web.Script.Serialization.
                         JavaScriptSerializer().Deserialize<List<Option>>(jsonArrayObject);

Json.Net

List<Option> optionList = JsonConvert.DeserializeObject<List<Option>>(jsonArrayObject);

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