在使用 System.Text.json 爬行 数据到 SQL Server 期间,我试图从 json 对象获取值。 json数据的结构是这样的:
skus:
1v9beswiav1wo91j:{...,...}
关键
1v9beswiav1wo91j
对我来说是遥不可及的,所以我使用JsonNode skus = item["skus"].AsObject().ElementAtOrDefault(0).Value;
来获取它的第一个值并做一些解析工作。
但是,在前几千圈的时候还可以。但它很快就会抛出
System.ArgumentException: An item with the same key has already been added. Key: 0rdfs1976wzsx8lj (Parameter 'propertyName')
。 而钥匙0rdfs1976wzsx8lj
正是上面的钥匙。
整个错误文本:
System.ArgumentException: An item with the same key has already been added. Key: 0rdfs1976wzsx8lj (Parameter 'propertyName')
at System.Text.Json.ThrowHelper.ThrowArgumentException_DuplicateKey(String paramName, String propertyName)
at System.Text.Json.Nodes.JsonObject.InitializeIfRequired()
at System.Text.Json.Nodes.JsonObject.GetEnumerator()
at System.Linq.Enumerable.TryGetElement[TSource](IEnumerable`1 source, Int32 index, TSource& element)
at System.Linq.Enumerable.ElementAtOrDefault[TSource](IEnumerable`1 source, Int32 index)
at BlazorApp1.Server.Jobs.HFJob.Execute(IJobExecutionContext context) in D:\repos\BlazorApp1\Server\Jobs\HFJob.cs:line 67
以及我使用的功能:
while (true)
{
using HttpClient client = new(new HttpClientHandler() { CookieContainer = cookies }) { BaseAddress = baseUri };
var post = await client.PostAsync(url, content);
JsonNode jsonNode = JsonNode.Parse(await post.Content.ReadAsStringAsync());
JsonArray jsonArray = jsonNode["results"].AsArray();
if (jsonArray.Count != 0)
{
foreach (var item in jsonArray)
{
JsonNode skus = item["skus"].AsObject().ElementAtOrDefault(0).Value;
Product product = new()
{
parsing work;
};
Product product1 = await _context.Products.FindAsync(keyValues: product.Id);
if (product1 != null)
{
update entity;
}
else
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
}
}
}
else
{
break;
}
}
我猜主要原因可能是重复将json对象入栈,两个相同Key的json对象冲突
但我没有使用任何数组或哈希集结构来恢复对象,这些json对象在解析后应该被销毁,新创建的对象如何与被销毁的对象冲突?
顺便说一句,理论上不应该有两个具有相同Key的json对象,因为我爬取的每一个数据都依赖它来识别。
我怀疑也可能存在并发问题,在两个不同的生命周期错误地请求两次相同的数据。我使用 Quartz.net 托管此服务。 请帮助我,我不知道如何解决这个问题。
Json数据详情
skus:{
"5c5cnedd7mo7m9qf": {
"allowBargain": false,
"bigPackAmount": 1,
"buyAmount": 1,
"canSell": true,
"count": 0,
"extendCode": "",
"hasStock": false,
"innerSellCtrlTags": "",
"lastAmount": 0,
"limitBuyAmount": 2147483647,
"middlePackAmount": 1,
"minAmount": 1,
"minOrder": 1,
"modCount": 1,
"oldPrice": 0,
"orgOldPrice": -1,
"orgPrice": -1,
"packAmount": 1,
"packDesc": "",
"packUnits": "",
"photo": null,
"price": 99999,
"priceEndDiff": "",
"priceEndTime": "",
"priceOfOrg": null,
"priceTip": "",
"priceType": "",
"sellCtrlTags": "(041)",
"sellStateTip": "",
"skuCode": "22459",
"skuId": "5c5cnedd7mo7m9qf",
"specDesc": "",
"specValueDef": "",
"specialPrice": -1,
"stepPriceDesc": "",
"stockTag": {
"amount": 0,
"stockState": "",
"stockType": ""
},
"tokenPrice": 0,
"units": "",
"weight": 0
}
}
我试图在一个圆圈的末尾销毁 json 对象,但我找不到手动处理它的方法,自动 GC 接管了应用程序的整个生命周期。并且并发问题很难追踪和确定它的错。