JSON

  1. last week

    Paulo C

    Nov 30 Brazil

    I would like to import a JSON returned from one brazilian zip code webservice. My Xojo code is:

    Dim Socket As New HTTPSocket
    Dim result As String
    Dim jsonData As Text
    
    Socket.SetRequestContent("", "application/json; charset=utf-8")
    result = Socket.get("viacep.com.br/ws/29042765/json/", 30)
    jsonData = DefineEncoding(result, Encodings.UTF8).ToText
    
    Dim d As Xojo.Core.Dictionary
    d = Xojo.Data.ParseJSON(jsonData)
    
    Dim theAdress As Xojo.Core.Dictionary = d.Value(1)
    Dim cep As Text = theAdress.Value("cep")
    Dim logradouro As Text = theAdress.Value("logradouro")

    the JSON received from webservice is:

    {
      "cep": "01001-000",
      "logradouro": "Praça da Sé",
      "complemento": "lado ímpar",
      "bairro": "Sé",
      "localidade": "São Paulo",
      "uf": "SP",
      "unidade": "",
      "ibge": "3550308",
      "gia": "1004"
    }

    My code doesn't work, with many erros. Could someone help-me?

    It should be maybe:

    // UNUSED Dim theAdress As Xojo.Core.Dictionary = d.Value(1)
    Dim cep As Text = d.Value("cep")
    Dim logradouro As Text = d.Value("logradouro")

    Since what you receive is an object not an array

  2. Antonio R

    Nov 30 Pre-Release Testers, Xojo Pro Answer Europe (Italy)

    It should be maybe:

    // UNUSED Dim theAdress As Xojo.Core.Dictionary = d.Value(1)
    Dim cep As Text = d.Value("cep")
    Dim logradouro As Text = d.Value("logradouro")

    Since what you receive is an object not an array

  3. Kem T

    Nov 30 Pre-Release Testers, Xojo Pro, XDC Speakers New York

    You didn't specify what the errors were, but right away I can see that you can't get d.Value( 1 ). First, the keys to JSON are case-sensitive strings, so "1" wouldn't work anyway, but there isn't even the string "1". I think you are trying to get the top level, but ParseJSON already does that for you. All you need is:

    dim cep as text = d.Value( "cep" )
  4. Paulo C

    Nov 30 Brazil

    Perfect! Saluti

or Sign Up to reply!