venerdì 11 febbraio 2022

JSon in Go

 Leggere Json in Go non e' esattamente banale perche' il linguaggio e' fortemente tipizzato

Se il tracciato record del Json e' fissato e' conosciuto si puo' fare un Unmarshal del tracciato altrimenti con Json dinamici o non conosciuti la situazione diventa piu' complessa

Partiamo da un Json complesso

---------------------------------------------------------------------------

 {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":
                "wguest",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c4cefc3032e3f8e63f3ee320b81cf1d5"
                    }
            }
    }

---------------------------------------------------------------------------

per fare l'Unmarshal del Json si deve definire tramite Struct il tracciato record con indicato anche il tipo di variabile associata ad ogni campo...in questo campo essendoci piu' livelli si devono creare delle Struct intermedie per i livelli piu' interni. Da notare che le variabilenelle Struct hanno la prima lettera maiuscola per l'esportazione ed il tag Json corrispondente

Interessa arriva a leggere la proprieta' idUserSession dell'utente (si tratta di gestire una authorization da un servizio Restful)

---------------------------------------------------------------------------

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    UserId        int32  `json:"userId"`
    UserName      string `json:"userName"`
    UserSurname   string `json:"userSurname"`
    IdUserSession string `json:"idUserSession"`
}

type dataValue struct {
    VersionWS            string `json:"versionWS"`
    Language             string `json:"it"`
    IdUserSession        string `json:"idUserSession"`
    Wguest string `json:"wguest"`
    User                 User   `json:"user"`
}

type messaggio struct {
    StatusCode int32     `json:"statusCode"`
    Message    string    `json:"message"`
    DataValue  dataValue `json:"dataValue"`
}

func main() {
    b := []byte(`    {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":"",
                "guest":"",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c"
                    }
            }
    }`)
    var mes messaggio
    json.Unmarshal(b, &mes)
    fmt.Println(mes.DataValue.User.IdUserSession)

}

---------------------------------------------------------------------------

fino a qui e' abbastanza lineare. Senza il tracciato record non si puo' fare Unmarshal di una Struct ma si deve passare attraverso una interface e gestire i vari livelli di map fino a trovare il valore richiesto


---------------------------------------------------------------------------
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`    {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":"":
                "guest":"",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c"
                    }
            }
    }`)

    var dat map[string]interface{}

    if err := json.Unmarshal(b, &dat); err != nil {
        panic(err)
    }
    test := dat["dataValue"].(map[string]interface{})["user"]
    if rec, ok := test.(map[string]interface{}); ok {
        for key, val := range rec {
            if key == "idUserSession" {
                fmt.Printf(" %s = %s", key, val)
                fmt.Println()
            }

        }
    }

}

---------------------------------------------------------------------------



Nessun commento:

Posta un commento

ESP32-2432S028R e LVGL

La scheda ESP32-2432S028R monta un Esp Dev Module con uno schermo TFT a driver ILI9341 di 320x240 pixels 16 bit colore.Il sito di riferiment...