如何从JSON字符串获取值?

时间:2015-06-12 18:21:55

标签: c# json json.net

我将集合转换为JSON字符串。

ReadOnlyCollection<Post> wall = api.Wall.Get(-group.Id.Value, out totalCount, count);
string json = JsonConvert.SerializeObject(wall, Formatting.Indented);

像这样获取字符串json

 [
  {
    "Id": 144159,
    "Text": "Если",
    "Likes": {
      "Count": 9307,
      "UserLikes": false,
      "CanLike": true,
      "CanPublish": true
    },
    "PostType": "post",
    "PostSource": {
      "Type": "api",
      "Data": null
    },
    "Attachments": [
      {
        "Instance": {
          "AlbumId": -7,
          "Photo75": "http://cs629506.vk.me/v629506780/3a56/Sn3eI5qEtc0.jpg",
          "Photo130": "http://cs629506.vk.me/v629506780/3a57/tKRNTJlSH1s.jpg",
          "Photo604": "http://cs629506.vk.me/v629506780/3a58/wyz6H7Py_8U.jpg",
        },
        "Type": "VkNet.Model.Attachments.Photo, VkNet, Version=1.0.16.0, Culture=neutral, PublicKeyToken=null"
      }
    ]

我如何从“Photo604”获得价值?我想得到图片网址。请帮帮我!

1 个答案:

答案 0 :(得分:1)

您需要首先将实例强​​制转换为照片:

var photo = wall[0].Attachments[0].Instance as Photo
if (photo != null)
    var uri = photo.Photo604

当然这里没有错误检查。您应该在访问之前检查空值和数组长度,否则可能会出现空引用异常。