将两个字符串列表转换为对象

时间:2017-04-17 12:08:00

标签: c# json list

我有以下基础json我通过解析excel表创建它:

{
"Rows": [{
    "RowId": "f7645b3e-a576-4cfe-a136-481d27b708cf",
    "Columns": ["Code", "Barcode", "SalesRep","Price"],
    "Values": ["bk101", "343131231", "Gambardella, Matthew","44.95"],
    "Status": "QUEUED"
}

我想进一步解析所提到的json的每一行到另一种类型,其中包含项目列表,例如:

{
  "Articles": [{
    "Id": "f7645b3e-a576-4cfe-a136-481d27b708cf"
    "Code": "bk101",
    "Barcode": "343131231",
    "SalesRep": "Gambardella, Matthew",
    "Price":"44.95"
  }]
}

如您所见,列和值已配对。 我知道我可以使用for循环来进行通过列和值列表的转换,但是还有另一种方法可以以有效的方式进行此转换吗?

1 个答案:

答案 0 :(得分:2)

JavaScriptSerializer ......

    public class Row
    {
        public string RowId { get; set; }
        public List<string> Columns { get; set; }
        public List<string> Values { get; set; }
        public string Status { get; set; }
    }

    public class RootRowObject
    {
        public List<Row> Rows { get; set; }
    }

    public class Article
    {
        public string Id { get; set; }
        public string Code { get; set; }
        public string Barcode { get; set; }
        public string SalesRep { get; set; }
        public string Price { get; set; }
    }

    string ConvertJson(string jsonRow)
    {
        RootRowObject rootRow = new 
               JavaScriptSerializer().Deserialize<RootRowObject>(jsonRow);

        List<Article> articles = rootRow.Rows.Select(x => new Article
        {
            Code = x.Values[0],
            Barcode = x.Values[1],
            Id = x.RowId,
            Price = x.Values[3],
            SalesRep = x.Values[2]
        }).ToList();

        return new JavaScriptSerializer().Serialize(articles);
    }