2017-12-28 32 views
0

나는 수학적 알고리즘을 응용 프로그램에 포함하도록 코딩하려고합니다.여러 수준의 JSON을 디코딩하고 데이터를 저장하는 방법은 무엇입니까?

많은 "레벨"을 반환하는 API에서 데이터를 가져 오는 중 14 개가 필요합니다. 나는 또한 그들을 사용하기 위해 각 "레벨"값을 저장할 필요가있다. (나는 가능한 한 자주 업데이트해야하지만 다른 스레드에 대해서는 같을 것이다). json으로의 시작처럼 보이는 방법은 다음과

은 다음과 같습니다

JSON Sample Screenshot

링크 : (? 배열) https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG 다음

내가 "0"레벨을 가져 오기 위해 노력하고 어떻게 데이터를없이 성공 :

struct Root : Decodable { 
    private enum CodingKeys : String, CodingKey { case data = "Data" }  
    let data : Data 
} 

struct Data : Decodable { 
    private enum CodingKeys : String, CodingKey { case zero = "0" } 
    let zero : Zero 
} 

struct Zero : Decodable { 

    private enum CodingKeys : String, CodingKey { 
     case time 
     case open 
     case high 
     case low 
     case close 
    } 
    let time : Double 
    let open : Double 
    let high : Double 
    let low : Double 
    let close : Double 
} 

및 ...

let marketData0 = try? JSONDecoder().decode(Root.self, from: data) 

0에서 13까지의 "레벨"에서 데이터를 가져와 어떻게 계산하여 계산에 사용할 수 있습니까?

+1

구문 분석에 대한 질문을 할 때 JSON 문자열의 예를 포함시키는 것이 가장 좋습니다. 이미지가 실제 문자열만큼 도움이되지 않습니다. – ColGraff

+0

JSON 링크를 추가해도 괜찮습니까? – Wizzardzz

+0

링크에 실제 "레벨"값이 없습니다. 'Data'는 단순히 JSON 배열입니다. – ColGraff

답변

0
import Foundation 

// Response "Data" key array elements 
struct Level: Codable { 
    let time: Double 
    let close: Double 
    let high: Double 
    let low: Double 
    let open: Double 
    let volumefrom: Double 
    let volumeto: Double 
} 

// The whole response (with some keys missing) 
struct Response: Codable { 
    let response: String 
    let type: Int 
    let aggregated: Bool 
    let data: [Level] // Translates the JSON array 

    // custom key names 
    private enum CodingKeys : String, CodingKey { 
    case data = "Data" 
    case response = "Response" 
    case type = "Type" 
    case aggregated = "Aggregated" 
    } 
} 

// The actual JSON String (shortened to two array members) 
let json = """ 
{"Response":"Success", 
"Type":100, 
"Aggregated":true, 
"Data":[ 
    {"time":1514469240,"close":14090.41,"high":14119.99,"low":14077.7,"open":14093.54,"volumefrom":189.71,"volumeto":2696906.84}, 
    {"time":1514469420,"close":14127.84,"high":14131.19,"low":14081.38,"open":14090.41,"volumefrom":197.76,"volumeto":2805972.44}], 
"TimeTo":1514480160, 
"TimeFrom":1514469240, 
"FirstValueInArray":true, 
"ConversionType":{ 
    "type":"direct", 
    "conversionSymbol":""}} 
""" 

// Make the String into a Data and decode it 
if let jsonData = json.data(using: .utf8), 
    let decoded = try? JSONDecoder().decode(Response.self, from: jsonData) { 
    // print all the decoded objects 
    print(decoded) 

    // print the decoded Data object at index 0 
    print("\n", decoded.data[0]) 
} 

// Decoded objects: 

/** Response(response: "Success", type: 100, aggregated: true, data: [ 
    __lldb_expr_15.Level(time: 1514469240.0, close: 14090.41, high: 14119.99, low: 14077.700000000001, open: 14093.540000000001, volumefrom: 189.71000000000001, volumeto: 2696906.8399999999), 
    __lldb_expr_15.Level(time: 1514469420.0, close: 14127.84, high: 14131.190000000001, low: 14081.379999999999, open: 14090.41, volumefrom: 197.75999999999999, volumeto: 2805972.4399999999)]) */ 

// Data object at index 0: 

/** Level(time: 1514469240.0, close: 14090.41, high: 14119.99, low: 14077.700000000001, open: 14093.540000000001, volumefrom: 189.71000000000001, volumeto: 2696906.8399999999) */ 
+0

시간 내 주셔서 감사합니다. 여기서하고있는 것을 얻지 못합니다. 수동으로 모든 것을 입력하지 않고 API에서 데이터를 가져와야하나요, 아니면 제가 누락 되었습니까? 상단의 "응답", "유형"및 "집계"는 단순히 응답 기능 없이는 데이터를 사용할 수 없다는 의미입니까? JSON을 처음 접했습니다. 실례합니다. – Wizzardzz

+0

완전한 예제로 제공되는 JSON 문자열을 포함하고 있습니다. 대신 API에서 데이터를 가져 와서 가져온 문자열을 사용합니다. 내가하고있는 일은 JSON에서 데이터 구조를 정의한 다음이를 디코딩하는 것이다. 당신은 열쇠 "데이터"와 배열을 포함하는 주요 하나있다. 메인 애트리뷰트가 검색되면 스위프트의 다른 'Array'처럼 "데이터"의 각 멤버를 가져올 수 있습니다. – ColGraff

+0

오, 알았어! 나는 놀이터에 코드를 복사하고 거기에서 시작하여 예제와 함께 필요한 것을 만들 것입니다. 대단히 감사합니다. – Wizzardzz