如何直接将子JSON读入集合?

时间:2013-10-14 13:11:55

标签: c# json

我从2个来源获得了一些数据。其中一个是以孩子json的形式发送所需的数据。

"Shifts": [
        {
            "Shift": {
                "ShiftID": 126604,
                "Name": "Volunteers - High Intensity",
                "Description": "sfsd",
                "Venue": "",
                "StartDateTime": "2014-01-28T12:00:00",
                "EndDateTime": "2014-01-28T16:30:00",
                "LocationN": "0.0",
                "LocationE": "0.0"
            }
        }
]
与其他来源相比,

深一级:

"Shifts": [
            {
                    "ShiftID": 126604,
                    "Name": "Volunteers - High Intensity",
                    "Description": "sfsd",
                    "Venue": "",
                    "StartDateTime": "2014-01-28T12:00:00",
                    "EndDateTime": "2014-01-28T16:30:00",
                    "LocationN": "0.0",
                    "LocationE": "0.0"
            }
    ]

我正在阅读这段代码:

var shiftProperty = json.GetValue("Shifts");
                        if (shiftProperty != null)
                        {
                            ObservableCollection<Shift> shift = new ObservableCollection<Shift>();
                            MemoryStream memorystream = new MemoryStream(Encoding.UTF8.GetBytes(shiftProperty.ToString()));
                            DataContractJsonSerializer serializer = new DataContractJsonSerializer(shift.GetType());
                            shift = serializer.ReadObject(memorystream) as ObservableCollection<Shift>;
                            App.RootFrame.Dispatcher.BeginInvoke(() =>
                            {
                                Shifts = shift;
                            });
                        }

我如何以与第二种格式相同的方式阅读第一种格式的数据?

1 个答案:

答案 0 :(得分:0)

{
"Shifts": [
    {
        "Shift": {
            "ShiftID": 126604,
            "Name": "Volunteers - High Intensity",
            "Description": "sfsd",
            "Venue": "",
            "StartDateTime": "2014-01-28T12:00:00",
            "EndDateTime": "2014-01-28T16:30:00",
            "LocationN": "0.0",
            "LocationE": "0.0"
        }
    }
]
}


public class Shift2
{
    public int ShiftID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Venue { get; set; }
    public string StartDateTime { get; set; }
    public string EndDateTime { get; set; }
    public string LocationN { get; set; }
    public string LocationE { get; set; }
}

public class Shift
{
    public Shift2 Shift { get; set; }
}

public class RootObject
{
    public List<Shift> Shifts { get; set; }
}

现在只需使用反序列化,下载程序集。我会建议http://james.newtonking.com/json

要创建JSON的C#类表示,可以使用http://json2csharp.com/