Swift解析含重复标识符的JSON:获取挪威能源API指定数据
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
ProdConsOverViewModelItementries. 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 thetitleTranslationIdmatches your target string. - Safe value extraction: We check that the
valueis 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

