I'm new to Go. I have been trying to get the photos from Flickr using their API but I'm facing an issue parsing the JSON response.
I have been writing the server in Go to handle the web service calls. My Output looks something like this:
{
"photos": {
"page": 1,
"pages": 3583,
"perpage": 100,
"total": "358260",
"photo": [
{
"id": "18929318980",
"owner": "125299498@N04",
"secret": "505225f721",
"server": "469",
"farm": 1,
"title": "❤️
The problem isn't with your model, that works just fine. You've already finished deserialzing (without errors) when the error occurs which is on this line; w.Write(jsonData.Photos.Photo[i].Id)
. You're passing an int when it needs to be a byte array.
This answer explains how to do the conversion; Convert an integer to a byte array
So, to make your code into some working form;
import "encoding/binary"
buffer := make([]byte, 4)
for i := 0;i < len(jsonData.Photos.Photo); i++ {
binary.LittleEndian.PutUint32(buffer, jsonData.Photos.Photo[i].Id)
w.Write(buffer)
}
Note that is writing the binary representation of your value as an unsigned 32 bit int with little endian bit order. That may not work for you. I can't say what will so you gotta make some decisions there like what bit order you want, if you need signed vs unsigned ect.
EDIT: To make the above work I guess you gotta do a cast from int to uint32 as well. Looking more closely at the answer I linked to you can do this instead which is cleaner/simpler imo.
import "strconv"
for _, p := range jsonData.Photos.Photo {
w.Write([]byte(strconv.Itoa(p.Id)))
}
Second EDIT: There's many ways to convert an int to binary. Another good option would be; func Write(w io.Writer, order ByteOrder, data interface{}) error
I believe in your code you could use that like;
import "encoding/binary"
for i := range jsonData.Photo.Photos {
binary.Write(w, binary.LittleEndian, jsonData.Photos.Photo[i].Id)
}
http://golang.org/pkg/encoding/binary/#Write
EDIT: Updated the three examples to have working for loops of different varieties.