gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:04:18 25 4
gpt4 key购买 nike

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

url1:

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

关于我应该选择什么流程有什么建议吗?

最佳答案

正如@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());

关于c# - 组合来自不同 URL 的 2 个 JSON 源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com