2017-06-15 77 views
0

我想從下面的字符串中獲取標籤的值。 我有這種格式的字符串。如何使用JavascriptSerializer反序列化C#中的json字符串

var string = "[{\"key\":\"182\",\"label\":\"testinstitution\"}]" 

dynamic dict = new JavaScriptSerializer().Deserialize<dynamic>(string); 

string inst = dict["label"]; //This is not working 

我得到的關鍵值對對象形式的字典,但我無法獲得標籤的價值。我不能使用JSON.NET。

+1

1 - 反序列化時是否收到任何錯誤? 2 - 訪問動態對象的「屬性」按名稱調用它:'string inst = dict.label;'3 - 您的JSON定義是一個數組,因此它應該是'string inst = dict [0] .label ;'4 - 如果你知道確切的結構,使用一個具體的類而不是動態的,它更有效。 – Gusman

+0

如果我檢查,然後我看到在這種形式的字典。 dict [0] [0]鍵「鍵」值「182」[1]鍵「標籤」值「testinstitution」。字典[0] .label不起作用。 –

回答

0

要從字符串中檢索標籤的值,請使用string inst = dict[0]["label"];

說明

爲什麼你需要額外[0]的原因是因爲反序列化返回數組鍵值對的。來自該陣列的第一個對象將指向索引[0],第二個對象從數組到索引[1]等。你的字符串只有一個對象的數組。這裏是當你有兩個對象,其中第二個對象有它內部的另一個對象,在這種情況下,你會寫
dict[1]["foo"]["two"]獲得所需值的示例:

var myString = @" 
    [ 
    { 
     'one': '1' 
    }, 
    { 
     'foo': 
     { 
     'two': '2' 
     } 
    } 
    ]"; 
dynamic dict = new JavaScriptSerializer().Deserialize<dynamic>(myString); 
string inst = dict[1]["foo"]["two"]; 

附加FYI

如果您知道數據結構,請考慮使用強類型(如其中一條註釋中所述)。下面是例子,你會怎麼做:

public class Data 
{ 
    public string key { get; set; } 
    public string label { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var myString = @" 
       [{ 
        'key': 182, 
        'label': 'testinstitution' 
       }]"; 
     List<Data> dict = new JavaScriptSerializer().Deserialize<List<Data>>(myString); 
     foreach (var d in dict) 
      Console.WriteLine(d.key + " " + d.label); 

     Console.ReadKey();    
    } 
} 

注意,在你的那些對象的數組正好在你的Data對象太多比賽的名稱屬性keyvalue

相關問題