【问题标题】:Converting two list of strings to an object将两个字符串列表转换为对象
【发布时间】:2017-04-17 12:08:00
【问题描述】:

我有以下基本 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 循环进行通过列和值列表的转换,但是还有另一种方法可以有效地进行这种转换吗?

【问题讨论】:

    标签: c# json list


    【解决方案1】:

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

    【讨论】:

    • 这确实比使用 for 循环要好得多。谢谢@caner! :]
    • 很高兴为您提供帮助 :)
    猜你喜欢
    • 2015-02-25
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2017-11-10
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多