0

I am reading a json document from localhost and trying to convert it to a Test type:

type Test struct {
    one string
    two string
    three string
}

res, err := http.Get("http://localhost/d/")
perror(err)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
perror(err)
var data Test
err = json.Unmarshal(body, &data)
if err != nil {
    fmt.Printf("%T\n%s\n%#v\n",err, err, err)
    switch v := err.(type){
    case *json.SyntaxError:
        fmt.Println(string(body[v.Offset - 40:v.Offset]))
    }
}


fmt.Println("response:")
fmt.Println(string(body))
fmt.Println("type:")
fmt.Println(data)

But the output shows an empty object:

response:
{
    "one" : "one thing",
    "two" : "two things",
    "three" : "3 things"

}
type:
{  }

What am I doing wrong?

localhost
  • 845
  • 3
  • 14
  • 32
  • 2
    What happens when you make your fields exported? That is.. uppercase first letters? `One`, `Two` and `Three` in the struct? – Simon Whitehead Sep 26 '14 at 00:59
  • 1
    possible duplicate of [Converting Go struct to JSON](http://stackoverflow.com/questions/8270816/converting-go-struct-to-json) – OneOfOne Sep 26 '14 at 01:04

1 Answers1

2

You have to export the struct fields, make them start with an uppercase letter.

OneOfOne
  • 95,033
  • 20
  • 184
  • 185