簡體   English   中英

進行JSON解析

[英]Go JSON parsing

我是新手。 我一直在嘗試使用其API從Flickr獲取照片,但是在解析JSON響應時遇到了問題。

我一直在Go中編寫服務器以處理Web服務調用。 我的輸出看起來像這樣:

{
    "photos": {
        "page": 1,
        "pages": 3583,
        "perpage": 100,
        "total": "358260",
        "photo": [
            {
                "id": "18929318980",
                "owner": "125299498@N04",
                "secret": "505225f721",
                "server": "469",
                "farm": 1,
                "title": "❤️🐾 Puppy Dog Eyes🐾❤️ #Cute #baby #havanese #puppy #love #petsofinstagram #akc #aplacetolovedogs #all_little_puppies #americankennelclub #beautiful #bestanimal #puppies #cutestdogever #dog #doglife #doglover #dogoftheday",
                "ispublic": 1,
                "isfriend": 0,
                "isfamily": 0
            },
            {
                "id": "18930020399",
                "owner": "125421155@N06",
                "secret": "449f493ebc",
                "server": "496",
                "farm": 1,
                "title": "Titt tei hvem er du for en liten tass 😊 Osvald og King 💜 #cat#kitten #bordercollie #puppy#dog",
                "ispublic": 1,
                "isfriend": 0,
                "isfamily": 0
            },
            {
                "id": "18929979989",
                "owner": "131975470@N02",
                "secret": "7da344edcb",
                "server": "498",
                "farm": 1,
                "title": "Shame, Shame",
                "ispublic": 1,
                "isfriend": 0,
                "isfamily": 0
            }
             ]
    },
    "stat": "ok"
}

當我嘗試運行代碼時,它顯示為:

cannot use jsonData.Photos.Photo[i].Id (type int) as type []byte in argument to w.Write

我的代碼如下:

package main

import(
        "os"
        "fmt"
        "log"
        "net/http"
        "io/ioutil"
        "encoding/json"
        "github.com/gorilla/mux"

)
type Result struct {
        Photos struct {
        Page int `json: "page"`
        Pages int `json: "pages"`
        PerPage int `json: "perpage"`
        Total int `json: "total"`
        Photo []struct {
            Id int `json: "id"`
            Owner string `json: "owner"`
            Secret string `json: "secret"`
            Server int `json: "server"`
            Farm int `json: "farm"`
            Title string `json: "title"`
            IsPublic int `json: "ispublic"`
            IsFriend int `json: "isfriend"`
            IsFamily int `json: "isfamily`
            } `json: "photo"`
    } `json: "photos"`
    Stat string `json: "stat"`
}

func main() {

    router := mux.NewRouter().StrictSlash(true);
    router.HandleFunc("/Index", Index)
    log.Fatal(http.ListenAndServe(":8084", router))
}

func Index(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json");
    url := "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6b54d86b4e09671ef6a2a8c02b7a3537&text=cute+puppies&format=json&nojsoncallback=1"
    res, err := http.Get(url)
     if err != nil{
        fmt.Printf("%s", err)
        os.Exit(1)
     }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil{
        fmt.Printf("%s", err)
        os.Exit(1)
     }

     jsonData := &Result{}
     err = json.Unmarshal([]byte(body), &jsonData)
     for i := 0;i < len(jsonData); i++ {
        w.Write(jsonData.Photos.Photo[i].Id)
     }
}

問題不在於您的模型,它很好用。 當發生此行上的錯誤時,您已經完成了反序列化(沒有錯誤); w.Write(jsonData.Photos.Photo[i].Id) 當需要一個字節數組時,您正在傳遞一個int。

該答案說明了如何進行轉換; 將整數轉換為字節數組

因此,使您的代碼成為某種可行的形式;

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

請注意,將您的值的二進制表示形式寫為無符號32位int,且其字節序少。 可能對您不起作用。 我不能說會怎樣,如果您需要帶符號對無符號等,那么您必須在其中做出一些決定,例如所需的位順序。

編輯:為了使上述工作,我想你也必須從int到uint32進行轉換。 更仔細地看我鏈接到您的答案可以做到這一點,它是更干凈/更簡單的imo。

import "strconv"

for _, p := range jsonData.Photos.Photo {
            w.Write([]byte(strconv.Itoa(p.Id)))
         }

第二編輯:有很多方法可以將int轉換為二進制。 另一個不錯的選擇是: func Write(w io.Writer, order ByteOrder, data interface{}) error

我相信您可以在代碼中使用類似的代碼;

  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

編輯:更新了三個示例,使其適用於不同品種的循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM