I'm posting the following json string:
{'foods':[{'vName':'bean','color':'green','size':'small'},
{'vName':'carrot','color':'orange', 'size':'medium'}]}
I'm posting to Go using Restangular, and the receiving func is:
func CreateFoods(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var food Food //this needs to be an array or something?
dec := json.NewDecoder(r.Body)
dec.Decode(&food)
}
My Food struct:
type Food struct{
VName string `json:"vName"`
Color string `json:"color"`
Size string `json:"size"`
}
I've used this routine for cases where where I post a single entity, but now I want to post multiple entities, and I cannot figure out how to map this json example to multiple entities. Also, I'm trying to "see" the JSON POST, to see the JSON string, then if I have to, I can work with the string to make the entities. I cannot figure out how to get a hold of the JSON string from http.Request.
Add this:
// You might use lowercase foods since it is maybe not something you want to export
type Foods struct {
Foods []Food
}
When decoding use this:
var foods Foods
dec.Decode(&foods)
To see the body of a response as a string:
bytes, err := ioutil.ReadAll(r.Body)
fmt.Println(string(bytes))
Small detail: After the last two lines you now read the body contents. You should then decode the json not using json.NewDecoder and Decode but json.Unmarshal. Complete example for CreateFoods() to prevent confusion:
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("error reading body")
return
}
fmt.Println(string(bytes))
var foods Foods
json.Unmarshal(bytes, &foods)
Hope it works, didn't test, let me know!
The proper way to handle decoding json if you have an io.Reader
is to use json.NewDecoder
, using ioutil.ReadAll
then json.Unmarshal
is slow and creates a lot of unneeded buffers.
To handle an array like your json example you need to create a struct like this:
type Foods struct {
Foods []Food `json:"foods"`
}
However if the json is just an array [{'vName':'bean','color':'green','size':'small'} {'vName':'carrot','color':'orange', 'size':'medium'}]
, you can just use:
type Foods []Food
type Food struct {
VName string `json:"vName"`
Color string `json:"color"`
Size string `json:"size"`
}
func CreateFoods(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var food Foods //this needs to be an array or something?
dec := json.NewDecoder(r.Body)
dec.Decode(&foods)
}