3

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

网址1:

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

网址2:

    {"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 文件。此外,由于格式不同,我在解析日期方面会遇到问题。

关于我应该走什么流程的任何建议?

4

1 回答 1

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());
于 2013-07-16T12:33:04.723 回答