2015-10-01 66 views
0

我需要構建一個只接收表名的web服務。無論C#中有多少列,都將表檢索到JSON。

我想在做這樣的事情:

public class Table 
{ 
    public string field{ get; set; } 
    public string value{ get; set; } 
} 

因爲我不知道用戶要什麼表,請求和多少列他們做的。

我正在使用WCF Web服務,我想以JSON格式檢索表;到目前爲止,我有這樣的事情(與3列的表格):

[{"field":"ID","value":"124"},{"field":"DES","value":"AValue"},{"field":"CODE","value":"ACode"},{"field":"ID","value":"125"},{"field":"DES","value":"AnotherV"},{"field":"CODE","value":"AnotherCode"}] 

正如你可以看到它是很難知道從哪裏行結束

有沒有一種方法來檢索在多個數據清晰的方式?

+0

爲什麼不能有Row和Column對象?事實上,你有一系列的表格,這不是你想要的 – Vlad274

+0

@ Vlad274請你詳細說明一下嗎? –

回答

0

您提供的模型實際上模型是單個單元格,而不是表格。

我建議你使用以下模型:

public class Row : Dictionary<string,string> 
{ 

} 

public class Table : List<Row> 
{ 

} 

然後你可以使用它像這樣:

Table table = new Table 
{ 
    new Row 
    { 
     {"Name", "Adam"}, 
     {"Age", "13"}, 
     {"Location","USA"} 
    }, 
    new Row 
    { 
     {"Name", "James"}, 
     {"Age", "19"}, 
     {"Location", "Europe"} 
    } 
}; 

下面是如何將這個對象序列化JSON的例子:

var result = JsonConvert.SerializeObject(table); 

此代碼使用JSON.NETTable對象序列化爲as特林。

這將產生以下JSON:

[{"Name":"Adam","Age":"13","Location":"USA"},{"Name":"James","Age":"19","Location":"Europe"}] 
0

如果你打算將建模表,你需要更細粒度:

public class Column 
{ 
    public string Name { get; set; } 
    public string Value { get; set; } 
} 

public class Row 
{ 
    public List<Column> Columns { get; set; } 
} 

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

然後創建數據:

var data = new Table() 
       { 
        new Row() 
         { 
          new Column() 
           { 
            Name = "Name", 
            Value = "Adam" 
           }, 
          new Column() 
           { 
            Name = "Age", 
            Value = "13" 
           }, 
          new Column() 
           { 
            Name = "Location", 
            Value = "USA" 
           } 
         }, 
        new Row() 
         { 
          new Column() 
           { 
            Name = "Name", 
            Value = "James" 
           }, 
          new Column() 
           { 
            Name = "Age", 
            Value = "19" 
           }, 
          new Column() 
           { 
            Name = "Location", 
            Value = "Europe" 
           } 
         } 
       } 

這將然後序列化爲

[ 
    { 
     { 
      "Name":"Name", 
      "Value":"Adam" 
     }, 
     { 
      "Name":"Age", 
      "Value":"13" 
     }, 
     { 
      "Name":"Location", 
      "Value":"USA" 
     } 
    }, 
    { 
     { 
      "Name":"Name", 
      "Value":"James" 
     }, 
     { 
      "Name":"Age", 
      "Value":"19" 
     }, 
     { 
      "Name":"Location", 
      "Value":"Europe" 
     } 
    } 
] 

是的這是更復雜,但我更喜歡,因爲它給你一個表的部分的強類型表示,但也允許相對容易的訪問數據。

@ Yacoub-Massad有一個很好的開始,它會爲你提供你需要的序列化。但我會建議一路走下去,因爲能夠序列化和反序列化爲強類型對象可以幫助捕獲編譯時錯誤,並且在序列化失敗時警告您(即錯誤的數據)

相關問題