如何使用JavascriptSerializer在C#中反序列化json字符串

时间:2017-06-15 18:59:35

标签: c# json

我试图从下面的字符串中获取标签的值。 我有一个这种格式的字符串。

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

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

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

我以键值对象的形式得到dict,但我无法获得标签的值。我不能使用JSON.NET。

1 个答案:

答案 0 :(得分: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();            
    }
}

请注意,key对象中的属性valueData与对象数组中的属性完全匹配。