从C#中的Json对象中提取multipe元素

时间:2017-01-16 21:32:54

标签: c# json

我想从以下json字符串

中读取循环中的SelectData值
[
  {
   "FlightCombination": {},
   "SelectData": "RwoAAB+LCAAAAAAABADNAA"
  },
  {
   "FlightCombination": {},
   "SelectData": "0QoAAB+LCAAAAAAABADA=="
  },
  {
   "FlightCombination": {},
   "SelectData": "WwoAAB+LCAAAAAAABAD" 
  }
]

到目前为止我的代码:

string flightselectkey;
dynamic dynObj = JsonConvert.DeserializeObject(flightlistingdetail);
foreach (var selectdata in dynObj) {
  flightselectkey = selectdata["SelectData"].ToString();
}

1 个答案:

答案 0 :(得分:1)

给出以下Json对象:

public class MyJsonObject
{
    public string FlightCombination { get; set; }
    public string SelectData { get; set; }
}

可以将json字符串反序列化为指定的.NET类型:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"[
          {
            ""FlightCombination"": ""{ }"",
            ""SelectData"": ""RwoAAB +LCAAAAAAABADNAA""
          },
          {
            ""FlightCombination"": ""{ }"",
            ""SelectData"": ""0QoAAB+LCAAAAAAABADA==""
          },
          {
            ""FlightCombination"": ""{ }"",
            ""SelectData"": ""WwoAAB +LCAAAAAAABAD""
          }
        ]";


        var jsonObject = JsonConvert.DeserializeObject<List<MyJsonObject>>(jsonString);

        List<string> dataList = jsonObject.Select(x => x.SelectData).ToList();

        dataList.ForEach(data =>
        {
            Console.WriteLine(data);
        });

        Console.ReadKey();

    }
}