2017-04-17 101 views
0

我有以下基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" 
    }] 
} 

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

回答

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

这个方式比使用循环确实比较好。感谢@caner! :] – Afflatus

+0

很高兴帮助:) – caner

相关问题