组合来自不同URL的2个JSON源

时间:2013-07-16 11:40:24

标签: c# json windows-phone json.net

我有来自两个不同网址的两个JSON文件:

URL1:

    {"2013" : [
        { "date":"2/5/2013 11:13 AM","height":3 }],
    "2012" : [
        { "date":"28/9/2012 3:34 PM","height":4 }]
    }

URL2:

    {"2013" : [
        { "date":"2013-01-09 12:00:00","height":0 },
        { "date":"2013-01-29 12:00:00","height":2 }],
    "2012" : [
        { "date":"2012-02-09 12:00:00","height":0 },
        { "date":"2012-02-29 12:00:00","height":2 }],
    "2011" : [
        { "date":"2011-03-09 12:00:00","height":3 },
        { "date":"2011-03-29 12:00:00","height":2 }]
    }

我想要发生的是将它们组合成这些:

    {"2013" : [
        { "date":"2013-05-02 11:13:00","height":3 },
        { "date":"2013-01-29 12:00:00","height":2 },
        { "date":"2013-01-09 12:00:00","height":0 }],
    "2012" : [
        { "date":"2012-09-28 15:34:00","height":2 },
        { "date":"2012-02-29 12:00:00","height":2 },
        { "date":"2012-02-09 12:00:00","height":0 }],
    "2011" : [
        { "date":"2011-03-29 12:00:00","height":2 },
        { "date":"2011-03-19 12:00:00","height":8 },
        { "date":"2011-03-09 12:00:00","height":3 }]
    }

目前,我要做的是两个单独的WebClient下载,然后尝试将它们组合(不成功)。我后来意识到做两个单独的WebClient下载,一个可能在我尝试组合它们之前没有完成,导致空引用。

    WebClient Url1 = new WebClient();
    Url1.DownloadStringCompleted += new      
        DownloadStringCompletedEventHandler(Url1_DownloadStringCompleted);
    Url1.DownloadStringAsync(new Uri("http://example.com"));
    WebClient Url2 = new WebClient();
    Url2.DownloadStringCompleted += new 
        DownloadStringCompletedEventHandler(Url2_DownloadStringCompleted);
    Url2.DownloadStringAsync(new Uri("http://anotherexample.com"));

    void Url1_DownloadStringCompleted(object sender,
        DownloadStringCompletedEventArgs e)
    {
    if (e.Error != null) return;
    json1 = JObject.Parse(e.Result);
    }

    void Url2_DownloadStringCompleted(object sender,
        DownloadStringCompletedEventArgs e)
    {
    if (e.Error != null) return;
    json2 = JObject.Parse(e.Result);
    }

到目前为止,我所读到的是排队,然后将其组合起来。但是,我不确定它是否有意义,因为它会使组合文件成为无效的JSON文件,因为括号不匹配。另外,由于格式不同,我在解析日期方面会遇到问题。

关于我应该去哪些流程的任何建议?

1 个答案:

答案 0 :(得分:2)

正如@cgatian所说,你应该创建一个新类:

public class Item
{
    public DateTime Date { get; set; }
    public int Height { get; set; }
}

然后:

    var dictionary1 = JsonConvert.DeserializeObject<Dictionary<int, Item[]>>(jsonFromUrl1);
    var dictionary2 = JsonConvert.DeserializeObject<Dictionary<int, Item[]>>(jsonFromUrl2);

    var mergedDictionary = dictionary1
        .Concat(dictionary2)
        .GroupBy(x => x.Key, y => y.Value)
        .ToDictionary(
            group => group.Key,
            group => group.SelectMany(x => x).ToArray());