2014-08-31 8 views
10

gram z Go i jestem zakłopotany, dlaczego json kodowania i dekodowania nie działa dla mnie(un) przetaczanie json golang nie działa

Myślę, że kopiowane przykłady niemal dosłownie, ale wyjście mówi zarówno marszałek, jak i niemiłosierny nie zwracają żadnych danych. Nie dają również błędu.

Czy ktoś może podpowiedzieć, dokąd zmierzam?

mój przykładowy kod: Go playground

package main 

import "fmt" 
import "encoding/json" 

type testStruct struct { 
    clip string `json:"clip"` 
} 

func main() { 
//unmarshal test 
    var testJson = "{\"clip\":\"test\"}" 
    var t testStruct 
    var jsonData = []byte(testJson) 
    err := json.Unmarshal(jsonData, &t) 
    if err != nil { 
     fmt.Printf("There was an error decoding the json. err = %s", err) 
     return 
    } 
    fmt.Printf("contents of decoded json is: %#v\r\n", t) 

//marshal test 
    t.clip = "test2" 
    data, err := json.Marshal(&t) 
    if err != nil { 
     fmt.Printf("There was an error encoding the json. err = %s", err) 
     return 
    } 
    fmt.Printf("encoded json = %s\r\n", string(data)) 
} 

wyjściowa:

contents of decoded json is: main.testStruct{clip:""} 
encoded json = {} 

w obu wyjść Liczyłam zobaczyć dekodowany lub zakodowane JSON

Odpowiedz

20

Na przykład

package main 

import "fmt" 
import "encoding/json" 

type testStruct struct { 
    Clip string `json:"clip"` 
} 

func main() { 
    //unmarshal test 
    var testJson = "{\"clip\":\"test\"}" 
    var t testStruct 
    var jsonData = []byte(testJson) 
    err := json.Unmarshal(jsonData, &t) 
    if err != nil { 
     fmt.Printf("There was an error decoding the json. err = %s", err) 
     return 
    } 
    fmt.Printf("contents of decoded json is: %#v\r\n", t) 

    //marshal test 
    t.Clip = "test2" 
    data, err := json.Marshal(&t) 
    if err != nil { 
     fmt.Printf("There was an error encoding the json. err = %s", err) 
     return 
    } 
    fmt.Printf("encoded json = %s\r\n", string(data)) 
} 

wyjściowa:

contents of decoded json is: main.testStruct{Clip:"test"} 
encoded json = {"clip":"test2"} 

Playground:

http://play.golang.org/p/3XaVougMTE

Eksport pola struct.

type testStruct struct { 
    Clip string `json:"clip"` 
} 

Exported identifiers

Identyfikator może być eksportowane w celu umożliwienia dostępu do niego z innego pakietu . Identyfikator jest eksportowany, jeśli zarówno:

  • pierwszy znak nazwy identyfikatora to wielka litera Unicode (klasa Unicode "Lu"); i
  • identyfikator jest zadeklarowany w bloku pakietu lub jest to nazwa pola lub nazwa metody.

Wszystkie pozostałe identyfikatory nie są eksportowane.

+1

wow ... Wiedziałem o wielkiej rzeczy, ale nigdy nie zdawałem sobie sprawy, że to ma jakiś wpływ na kodowanie JSON'a (czy to słowo?). Dzięki za brak wglądu – Toad