如何优化返回JArray的商品分类函数及实现后续API批量查询?
现有实现的问题
首先你的现有代码本身存在几处明显错误和不合理设计:
- 无用冗余代码:
Dim tokenJson = JsonConvert.SerializeObject(jsonResponseText)完全没有作用,jsonResponseText本身就是字符串,不需要序列化,可以直接删除。 - JSON解析逻辑错误:你提供的JSON示例中
data是对象类型不是数组,jsonResult.Item("data").item(0)的写法会直接抛出索引不存在/空引用异常,不需要转Dictionary(Of String, Object),直接用JObject解析更简单。 - 异常处理有隐患:如果接口调用报错,
returnCatArray不会被赋值,会返回Nothing,后续遍历的时候直接触发空引用崩溃,至少要初始化默认返回空JArray。 - 你写的遍历逻辑存在参数错误:循环变量
idx是取到的分类ID,你调用GetCategorySpecificInfoById的时候还是传固定的产品ID123456,完全没有把分类ID传入接口,属于逻辑错误。
遍历方案的合理性
如果你的分类数量不多(通常≤10个)、接口响应速度快,修正参数后的同步遍历属于常规实现,符合业务开发的通用规范,没有原则性问题。如果分类数量多、接口响应慢,同步遍历会阻塞主线程,这种场景就需要更优的实现方案。
优化方案
基础优化(兼容现有同步逻辑)
先修正GetProductCategories函数的错误:
Function GetProductCategories(productid As String) As JArray ' 初始化返回空数组,避免异常时返回Nothing Dim returnCatArray As New JArray() Try ' 这里补充你自己的request构造逻辑,关联productid参数 Dim request As System.Net.WebRequest = System.Net.WebRequest.Create($"你的API接口地址?productid={productid}") Using response As System.Net.WebResponse = request.GetResponse() Using streamReader As New System.IO.StreamReader(response.GetResponseStream()) Dim jsonResponseText = streamReader.ReadToEnd() ' 直接用JObject解析,不需要转Dictionary Dim jsonResult = Newtonsoft.Json.Linq.JObject.Parse(jsonResponseText) returnCatArray = jsonResult("data")("categories").ToObject(Of JArray)() End Using End Using Catch ex As Exception ' 生产环境建议替换为日志记录,不要用MsgBox避免阻塞后台运行 Console.WriteLine($"获取分类失败:{ex.Message}") End Try Return returnCatArray End Function
修正后的遍历调用代码:
For Each catId In GetProductCategories("123456") ' 传入分类ID调用接口 GetCategorySpecificInfoById(catId.ToString()) Next
进阶优化(高并发/多分类场景)
如果分类数量多,建议改用异步并行调用,大幅降低总耗时:
' 异步获取分类列表 Async Function GetProductCategoriesAsync(productid As String) As Task(Of JArray) Dim returnCatArray As New JArray() Try Dim client As New System.Net.Http.HttpClient() Dim jsonResponseText = Await client.GetStringAsync($"你的API接口地址?productid={productid}") Dim jsonResult = Newtonsoft.Json.Linq.JObject.Parse(jsonResponseText) returnCatArray = jsonResult("data")("categories").ToObject(Of JArray)() Catch ex As Exception Console.WriteLine($"获取分类失败:{ex.Message}") End Try Return returnCatArray End Function ' 异步查询分类详情 Async Function GetCategorySpecificInfoByIdAsync(catId As String) As Task(Of Object) Dim client As New System.Net.Http.HttpClient() Return Await client.GetStringAsync($"你的分类详情接口地址?catid={catId}") End Function
并行调用示例:
' 先获取全部分类ID Dim catIds = Await GetProductCategoriesAsync("123456") ' 生成所有查询任务 Dim queryTasks = catIds.Select(Function(id) GetCategorySpecificInfoByIdAsync(id.ToString())).ToList() ' 等待所有任务执行完成,总耗时≈最慢的单个接口耗时 Dim allResults = Await Task.WhenAll(queryTasks) ' 后续统一处理所有返回结果
内容的提问来源于stack exchange,提问作者Byte
相关产品推荐
相关产品推荐

