如何提取 JSON 数组中与特定键相关的信息?
我有一个带有卖家信息和可用模型的移动股票 json,如下所示
{
"title": "mobile_stock_information",
"payload": {
"sellers": [
{
"seller": "SAMSUNG",
"phone_model": "Samsung S21"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S21 Ultra"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S22"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S22 Ultra"
},
{
"seller": "APPLE",
"phone_model": "Iphone 13"
},
{
"seller": "APPLE",
"phone_model": "Iphone 13 Pro"
},
{
"seller": "APPLE",
"phone_model": "Iphone 12"
},
{
"seller": "GOOGLE",
"phone_model": "Pixel 6"
},
{
"seller": "GOOGLE",
"phone_model": "Pixel 6 XL"
},
{
"seller": "GOOGLE",
"phone_model": "Pixel 5"
}
]
}
}
我正在使用 Jayway JSON Path 从 Json 中提取所有卖家,如下所示
String sellerPath = "$.payload.sellers[*].seller";
DocumentContext jsonContext = JsonPath.parse(seller_json);
List<String> sellersList = jsonContext.read(sellerPath);
Set<String> sellerSet = new HashSet<>(sellersList);
我将列表转换为 Set 以获取唯一的卖家,之后我将迭代 JSONArray 并尝试提取移动卖家特定数据
sellersArray = sellerJSON.getJSONArray("sellers");
public static JSONObject getSellerObject(String sellerToSearch, JSONArray array) {
for(int i = 0; i < array.length(); i++) {
try {
JSONObject jsonObject = array.getJSONObject(i);
if (jsonObject.getString("seller").equals(sellerToSearch)){
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
输出如下所示
{
"title": "mobile_stock_information",
"payload": {
"sellers": [
{
"seller": "SAMSUNG",
"phone_model": "Samsung S21"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S21 Ultra"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S22"
},
{
"seller": "SAMSUNG",
"phone_model": "Samsung S22 Ultra"
}
]
}
}
假设我有 5 个不同的供应商和卖家数组内的 10 个 json 对象,我必须为每个密钥迭代循环 10 次,对于 5 个密钥将是 50 次。有没有有效的方法来减少迭代次数并提取供应商特定信息。提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 JSON 的一次传递中创建卖家/供应商及其模型的映射。您所需要做的就是编写一个
Map>
,其中键是卖家,值是他们拥有的型号列表。然后,您可以检索任何特定卖家的模型列表,而无需迭代 JSON。从此时起,您可以查询任何特定卖家的
sellerModels
,并获取其模型列表,而无需再次迭代 JSON。You can create in one pass of the JSON a Map of seller/vendor and their models. All you need is to do is to compose a
Map<String, List<String>>
where the key is the seller and the value is the list of models they have. Then you can retrieve the list of models for any specific seller without iterating over the JSON.From this point you can query
sellerModels
for any particular seller, and get a list of its models without iterating over the JSON ever again.