douluan5738 2014-10-01 02:17
浏览 134
已采纳

在使用Gorilla的Go ReST服务中处理JSON

I have a Go ReST service that receives JSON, and I need to edit the JSON so I may make two different structs.

My structs:

type Interaction struct{

 DrugName string `json:"drugName"`
 SeverityLevel string `json:"severityLevel"`
 Summary string `json:"summary"`
}

type Drug struct {
 Name string `json:"drugName"`
 Dosages []string `json:"dosages"`
 Interactions []Interaction `json:"interactions"`
}

Example JSON being sent:

{"drugName":"foo","dosages":["dos1"],"interactions":[["advil","high","summaryForAdvil"]]}

The ReST service:

func CreateDrug(w http.ResponseWriter, r *http.Request) {

  //I verified the received JSON by printing out the bytes:
  bytes, _ := ioutil.ReadAll(r.Body)
}

My goal is the make two different JSONs in the CreateDrug function so I may make the two different structs, Drug and Interaction:

{"drugName":"foo","dosages":["dos1"]}
{"drugName":"advil", "severityLevel":"high", "summary":"summaryForAdvil"}

In Go, in this function, how do I use the received JSON to make two new JSONs?

  • 写回答

2条回答 默认 最新

  • doucanshou6998 2014-10-01 02:34
    关注

    Unmarshal the request to a struct matching the structure of the request, copy values to the structs you have defined, and marshal to create the result.

    func CreateDrug(w http.ResponseWriter, r *http.Request) {
    
      // Unmarshal request to value matching the structure of the incoming JSON
    
      var v struct {
        DrugName     string
        Dosages      []string
        Interactions [][3]string
      }
      if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
        // handle error
      }
    
      // Copy to new struct values.
    
      var interactions []Interaction
      for _, i := range v.Interactions {
        interactions = append(interactions, Interaction{DrugName: i[0], SeverityLevel: i[1], Summary: i[2]})
      }
    
      drug := &Drug{Name: v.DrugName, Dosages: v.Dosages, Interactions: interactions}
    
      // Marshal back to JSON.
    
      data, err := json.Marshal(drug)
      if err != nil {
          // handle error
      }
    
      // Do something with data.
    }
    

    <kbd>Playground link</kbd>

    (I am assuming that you want a single JSON value for Drug with the Interactions field filled in. If that's not what you want, marshal the Drug and Interactions values separately.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度