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

相关问题