解组json的问题

Here's a simplified version what I'm trying to do:

type example struct {
    Topics []struct {
        Id int64 `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
        Tags []string `json:"tags"`
        Search_phrases []string `json:"search_phrases"`
    } `json:"topics"`
}

func main() {
    body := []byte(
`
{
    "topics": [{
    "id":              35436,
    "title":           "How to Disassemble the ED209",
    "body":            "Carefully with very large pliers",
    "tags":            ["danger"],
    "search_phrases":  ["red", "yellow"]
  }]
}
`)
    var topics []example
    err := json.Unmarshal(body, &topics)

    if err != nil {
        fmt.Println(err)
    }
/*
    for _, topics := range topics {
        //doSomething
    }
*/
}

This looks fine to me, but I am getting:

"json: cannot unmarshal object into Go value of type []main.example"

I'm probably just missing something small, but I can't seem to find it at the moment.

The error really explains the problem, you're trying to use []example where your json example is an object not an array, simply change it to:

var ex example
err := json.Unmarshal(body, &ex)

if err != nil {
    fmt.Println(err)
}
fmt.Println(ex.Topics)

playground

You are trying to unmarshal a single element into a list. Use a single element instead.

http://play.golang.org/p/g4Fblu_YRP

package main

import (
    "encoding/json"
    "fmt"
)

type example struct {
    Topics []struct {
        Id             int64    `json:"id"`
        Title          string   `json:"title"`
        Body           string   `json:"body"`
        Tags           []string `json:"tags"`
        Search_phrases []string `json:"search_phrases"`
    } `json:"topics"`
}

func main() {
    body := []byte(
        `
{
    "topics": [{
    "id":              35436,
    "title":           "How to Disassemble the ED209",
    "body":            "Carefully with very large pliers",
    "tags":            ["danger"],
    "search_phrases":  ["red", "yellow"]
  }]
}
`)
    var topic example
    err := json.Unmarshal(body, &topic)

    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%#v
", topic)
    /*
       for _, topics := range topics {
           //doSomething
       }
    */
}