0

I need to convert a let JSON string to an object. Here are some code with an example but it doesn't work

   let json = "{ \"data\": [ { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18734, \"unidadeCurricularNome\": \"Algoritmos e Estruturas de Dados\", \"unidadeCurricularAbreviatura\": \"AED\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 6 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Programação Avançada\", \"unidadeCurricularAbreviatura\": \"PA\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Álgebra Linear\", \"unidadeCurricularAbreviatura\": \"AlgL\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"1\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 1, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 } ] }";


    let data = json.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
        {
            let ucIdMapSiges = jsonArray["unidadeCurricularIdMapSiges"] as! Int
            let ucNome = jsonArray["unidadeCurricularNome"] as! String
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }
2
  • Cannot subscript a value of type '[Dictionary<String, Any>]' with an index of type 'String' got this error Commented May 14, 2019 at 11:36
  • 3
    Possible duplicate of Convert Json string to Json object in Swift 4 Commented May 14, 2019 at 11:42

2 Answers 2

1

Your json root is a dictionary where data key is an array so try

do { 
        if let jsonArray = try JSONSerialization.jsonObject(with:Data(json.utf8), options :[]) as? Dictionary<String,Any> , let data = jsonArray["data"] as? [[String:Any]] {  
            data.forEach { 
               let ucIdMapSiges = $0["unidadeCurricularIdMapSiges"] as? Int
               let ucNome = $0["unidadeCurricularNome"] as? String

               print(ucIdMapSiges,ucNome)

            } 
        } 
    }
   catch {
        print(error)
   }

It's also better to

do {

     let res = try JSONDecoder().decode(Root.self, from:Data(json.utf8))
     print(res.data)
}
catch {
    print(error)
}



struct Root : Codable {
    let data:[Model]
}

struct Model : Codable {
    let unidadeCurricularIdMapSiges:Int
    let unidadeCurricularNome:String
}
Sign up to request clarification or add additional context in comments.

2 Comments

Change from try JSONSerialization. to try? JSONSerialization. only makes it harder to debug.
@user28434 anyway i know it'll work and didn't want it to be try! / try
0

jsonArray is a Dictionary not Array. You need to get the array from dictionay by subscrpting with the key data

Try this

guard let data = json.data(using: .utf8) else {
    return
}
do {
    if let jsonDictionary = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
    {
        if let dataArray = jsonDictionary["data"] as? [[String:Any]] {
            for data in dataArray {
                if let ucIdMapSiges = data["unidadeCurricularIdMapSiges"] as? Int,
                    let ucNome = data["unidadeCurricularNome"] as? String {
                        print(ucIdMapSiges)
                        print(ucNome)
                }
            }
        }

    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.