douganggu4392 2012-12-07 10:05
浏览 48

未编组的JSON不返回任何内容

I have the following struct:

type Translation struct{
  Data string
  Translations []struct{
    TranslatedText string
    SourceLanguage string
  }
}
type InputText struct {
  PlainText string
  TargetLanguage string
  Values url.Values
}

and a method that hits the Google Translate API and returns JSON string that I want to UnMarshal:

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)
}

When I run this code all I get is &{[]} printed out, I thought the JSON wasn't being returned but when I tried this in the TranslateString() method:

fmt.Println(string(body))

It prints out:

{
 "data": {
  "translations": [
   {
    "translatedText": "Mi nombre es John, nació en Nairobi y tengo 31 años de edad",
    "detectedSourceLanguage": "en"
   }
  ]
 }
}
  • 写回答

1条回答 默认 最新

  • drau89457 2012-12-07 11:45
    关注

    The code above is correct with one mistake, my struct is all wrong!! it should be:

    type Translation struct{
        Data struct {
            Translations []struct {
                TranslatedText string
                DetectedSourceLanguage string
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)