我有以下结构:
type Translation struct{
Data string
Translations []struct{
TranslatedText string
SourceLanguage string
}
}
type InputText struct {
PlainText string
TargetLanguage string
Values url.Values
}
以及一种点击Google Translate API并返回我想要UnMarshal的JSON字符串的方法:
func (i *InputText) TranslateString() (*Translation, error){
if len(i.PlainText) == 0 {
log.Fatal("No text specified")
}
if len(i.TargetLanguage) == 0 {
log.Fatal("No target language specified")
}
i.Values = make(url.Values)
var v = i.Values
v.Set("target", i.TargetLanguage)
v.Set("key", API_KEY)
v.Set("q", i.PlainText)
u := fmt.Sprintf("%s?%s", api, v.Encode())
getResp, err := http.Get(u)
if err != nil{
log.Fatal("error", err)
return nil, err
}
defer getResp.Body.Close()
body, _ := ioutil.ReadAll(getResp.Body)
t := new(Translation)
json.Unmarshal(body, &t)
return t, nil
}
func main(){
input := &InputText{"My name is John, I was born in Nairobi and I am 31 years old", "ES", nil}
translation, _ := input.TranslateString()
fmt.Println(translation)
}
当我运行此代码时,我得到的是&{[]}
打印出来的,我认为JSON没有被返回但是当我在TranslateString()方法中尝试这个时:
fmt.Println(string(body))
打印出来:
{
"data": {
"translations": [
{
"translatedText": "Mi nombre es John, nació en Nairobi y tengo 31 años de edad",
"detectedSourceLanguage": "en"
}
]
}
}
答案 0 :(得分:1)
上面的代码是正确的,有一个错误,我的结构都错了!!它应该是:
type Translation struct{
Data struct {
Translations []struct {
TranslatedText string
DetectedSourceLanguage string
}
}
}