You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift解析含重复标识符的JSON:获取挪威能源API指定数据

Fixing Your Norwegian Energy API Parsing Issue

Hey there! I see the problem you're running into — the API's response structure has multiple ProdConsOverViewModelItem entries under HydroData, and your current code is trying to access it as a single object instead of an array. Let's fix that step by step.

The Root Cause

Your original code assumes ProdConsOverViewModelItem is a single dictionary, but in reality, it's an array of dictionaries (since there are multiple identical nodes in the response). SwiftyJSON can't find the value key under a non-existent single item, hence the "parse fail" message.

Updated Parsing Code

Replace your updateEnergyData function with this version, which handles the array correctly and searches for the specific item you need:

func updateEnergyData(json : JSON){
    // First, extract the array of HydroData items
    guard let hydroItems = json["ProductionConsumptionOverviewViewModel"]["HydroData"]["ProdConsOverViewModelItem"].array else {
        print("No hydro items found or invalid response structure")
        return
    }
    
    // Search the array for the item with your target titleTranslationId
    if let targetHydroItem = hydroItems.first(where: { item in
        item["titleTranslationId"].string == "ProductionConsumption.HydroSEDesc"
    }) {
        // Extract the value if it exists
        if let hydroSEValue = targetHydroItem["value"].double {
            print("Hydro SE Production/Consumption Value: \(hydroSEValue)")
        } else {
            print("Could not extract numeric value from target item")
        }
    } else {
        print("Item with titleTranslationId 'ProductionConsumption.HydroSEDesc' not found")
    }
}

Key Changes Explained

  • Guard for the array: We first make sure we can access the array of ProdConsOverViewModelItem entries. If this fails, we get a clear error message instead of silent failure.
  • Search with first(where:): This iterates through the array and returns the first item where the titleTranslationId matches your target string.
  • Safe value extraction: We check that the value is a double before using it, avoiding unexpected crashes or nil values.

Quick Debug Tip

If you're still having trouble, add a print statement to inspect the array structure:

print("Hydro Items: \(hydroItems)")

This will let you verify that the titleTranslationId keys match exactly (case sensitivity matters!) and that the value field is indeed a numeric type.

内容的提问来源于stack exchange,提问作者Nisse82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:22:26