我已经把这个Go twitter客户端搞砸了,客户端在显示结果方面仍然需要一些工作,我想将JSON结果http://pastie.org/7298856表示为Go结构,我不是需要JSON结果中的所有字段,任何指针?
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
type TwitterResult struct{
}
var twitterUrl = "http://search.twitter.com/search.json?q=%23KOT"
func retrieveTweets(c chan<- string) {
for {
resp, err := http.Get(twitterUrl)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
c <- string(body)
}
}
func displayTweets(c chan string) {
fmt.Println(<-c)
}
func main() {
c := make(chan string)
go retrieveTweets(c)
for {
displayTweets(c)
}
}
答案 0 :(得分:2)
encoding/json
包提供了一种直接解压缩JSON的方法
结构。以下示例解析JSON内容(地图)并将字段分配给它们
struct标签标识的相应目标。例如,键"someId"
被映射到结构
带有标记json:"someId"
的字段。您可以使用代码here。
package main
import "fmt"
import "encoding/json"
type Example struct {
Id int `json:"someId"`
Content string `json:"someContent"`
}
func main() {
var xmpl Example
input := `{"someId": 100, "someContent": "foo"}`
json.Unmarshal([]byte(input), &xmpl)
fmt.Println(xmpl)
}
您可以在docs中找到有关语法的详细信息。 默认情况下会忽略结构中未提及的字段。
答案 1 :(得分:0)
我发现这个https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/dNjIs-O64do足以让我指向正确的方向。 更新:我的代码实现
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type twitterResult struct {
Results []struct {
Text string `json:"text"`
Ids string `json:"id_str"`
Name string `json:"from_user_name"`
Username string `json:"from_user"`
UserId string `json:"from_user_id_str"`
}
}
var (
twitterUrl = "http://search.twitter.com/search.json?q=%23UCL"
pauseDuration = 5 * time.Second
)
func retrieveTweets(c chan<- *twitterResult) {
for {
resp, err := http.Get(twitterUrl)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
r := new(twitterResult) //or &twitterResult{} which returns *twitterResult
err = json.Unmarshal(body, &r)
if err != nil {
log.Fatal(err)
}
c <- r
time.Sleep(pauseDuration)
}
}
func displayTweets(c chan *twitterResult) {
tweets := <-c
for _, v := range tweets.Results {
fmt.Printf("%v:%v\n", v.Username, v.Text)
}
}
func main() {
c := make(chan *twitterResult)
go retrieveTweets(c)
for {
displayTweets(c)
}
}
代码工作得很好,我只想知道创建一个指向结构的指针的通道是否是惯用的Go。