vkorbes / aprendago

Curso completo em português da linguagem Go, de zero a ninja! 🇧🇷
http://aprendago.com
988 stars 179 forks source link

Exercício: Capítulo 17, Exercício 2 (Nível: 8) #55

Open vkorbes opened 3 years ago

vkorbes commented 3 years ago

Exercício: Capítulo 17, Exercício 2 (Nível: 8)

Link para o vídeo:

Use esta thread para compartilhar sua solução, discutir o exercício com os colegas e pedir ajuda caso tenha dificuldades!

diegoparra commented 3 years ago

Esse deu um trabalhinho legal, tive que lembrar que tinha que criar um slice vazio do tipo do struct e passar o ponteiro como referencia pro Unmarshal.

https://play.golang.org/p/cgx1RqLqphI

an4kein commented 3 years ago

https://play.golang.org/p/qSUTgHHnkhF

Adaptar isso foi facil, inicialmente precisamos converter json-to-go e tomando como base um exemplo Unmarshal foi rapido fazer

package main

import (
    "encoding/json"
    "fmt"
)

/* - Partindo do código abaixo, utilize unmarshal e demonstre os valores.
    - https://play.golang.org/p/b_UuCcZag9​
- Dica: JSON-to-Go.
*/

type MyJsonName struct {
    Age     int64    `json:"Age"`
    First   string   `json:"First"`
    Last    string   `json:"Last"`
    Sayings []string `json:"Sayings"`
}

func main() {
    data := []byte(`[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`)

    //func Unmarshal(data []byte, v interface{}) error
    var lista []MyJsonName
    err := json.Unmarshal(data, &lista)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(lista)
}

Output

[{32 James Bond [Shaken, not stirred Youth is no guarantee of innovation In his majesty's royal service]} {27 Miss Moneypenny [James, it is soo good to see you Would you like me to take care of that for you, James? I would really prefer to be a secret agent myself.]} {54 M Hmmmm [Oh, James. You didn't. Dear God, what has James done now? Can someone please tell me where James Bond is?]}]

Program exited.
ghost commented 2 years ago

Usei o for para percorrer o blob de users e mostrar o resultado na tela.

Essa foi minha solução:

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    First   string   `json:"first"`
    Last    string   `json:"last"`
    Age     int      `json:"age"`
    Sayings []string `json:"sayings"`
}

func main() {
    blob := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
    var users []User

    err := json.Unmarshal([]byte(blob), &users)
    if err != nil {
        fmt.Println(err)
    }

    for _, user := range users {
        fmt.Println("Olá meu nome é", user.First, user.Last)
        fmt.Println("Tenho", user.Age, "anos")
        fmt.Println("Sayings")
        for _, v := range user.Sayings {
            fmt.Println("-", v)
        }
    }

}

Go Playground: https://play.golang.org/p/rslxHnGFVO2

wfrsilva commented 2 years ago

Cap. 17 – Exercícios: Nível #8 – 2 https://go.dev/play/p/pk8CO-z637b

image

Harsgaard commented 1 year ago

https://go.dev/play/p/4uCTS446Unz

LelecoNN commented 9 months ago

https://go.dev/play/p/Kh476CfD-92

package main

import ( "encoding/json" "fmt" )

type Toneio []struct { First string json:"First" Age int json:"Age" }

func main() { tr := []byte([{"First":"James","Age":32},{"First":"Moneypenny","Age":27},{"First":"M","Age":54}]) var coisa Toneio er := json.Unmarshal(tr, &coisa) if er != nil { fmt.Println(er)

}
fmt.Println(coisa)

}