2017-03-31 34 views
-3

我正在使用C#。我想JSON數組在下面的結構如何將值分配給嵌套的Json數組

"bed_configurations": [ 
      [{ 
      "type": "standard", 
      "code": 3, 
      "count": 1 
      }, 
      { 
       "type": "custom", 
       "name": "Loft", 
       "count": 1 
      }] 
     ] 

請任何一個能幫助我..

+1

什麼是你的目標,你想創建這樣的結構從類,創建它?指定一個你想實現的具體事物,並向我們展示你迄今爲止開發的代碼。 –

+0

爲什麼你需要在這個json中只包含一個數組的數組中的數組? –

+0

嗨Mr.Rafal,我想從類創建json數組結構,我想知道如何創建類以及如何將數據庫中的值分配給此結構。 – Vicky

回答

1

你必須爲所需json創建class。你也必須使用using Newtonsoft.Json;作爲json轉換器。我已經創建了一個例子,請檢查一下。

CODE:

public class Header 
{ 
    public List<List<Item>> bed_configurations { get; set; } 
} 

public class Item 
{ 
    public string type { get; set; } 
    public int code { get; set; } 
    public string name { get; set; } 
    public int count { get; set; } 
} 

private static void getJSON() 
{ 
    List<Item> items = new List<Item>(); 
    items.Add(new Item() { type = "standard", code = 3, count = 1 }); 
    items.Add(new Item() { type = "custom", name = "Loft", count = 1 }); 

    Header ob = new Header(); 
    ob.bed_configurations = new List<List<Item>>() { items }; 

    string output = JsonConvert.SerializeObject(ob); 
} 

輸出:

enter image description here

+0

感謝您的回答。我會在謎底嘗試 – Vicky

+0

非常感謝。它工作正常....... – Vicky

+0

不客氣!!!!! – csharpbd

1

你最好的辦法是創建類似於這種結構的一類,並使用Newtonsoft.JSON序列化/從反序列化對象/一個json字符串。

public class BedConfiguration 
{ 
    [JsonProperty("type")] 
    public string Type {get; set;} 
    [JsonProperty("code")] 
    public int Code {get; set;} 
    [JsonProperty("count")] 
    public int Count {get; set;} 
} 

而整個json字符串只是一個數組,在上面的類(奇怪)。所以,你可以填充這些BedConfiguration的列表,然後它們序列:

var configs = new List<List<BedConfiguration>>(); 
//Populate the list programmatically. 
var json = JsonConvert.SerializeObject(configs); 

同樣,你可以把JSON字符串返回到一個列表:

var configs = JsonConvert.DeserializeObject<List<List<BedConfiguration>>>(json); 
+0

是的,只是注意到它是一個數組中的數組。 – ThePerplexedOne