2017-03-03 79 views
-1
{ 
    "devices": [ 
    { 
     "id": 20081691, 
     "targetIp": "10.1.1.1", 
     "iops": "0.25 IOPS per GB", 
     "capacity": 20, 
     "allowedVirtualGuests": [ 
     { 
      "Name": "akhil1" 
     }, 
     { 
      "Name": "akhil2" 
     } 
     ] 
    } 
    ] 
} 

如何編寫此JSON數據的結構表示,以便我可以添加和刪除設備到列表中。我嘗試了不同的結構表示,但沒有任何工作。下面是我用類似的json數據嘗試過的例子之一。我無法向其添加新數據。該結構的代表性和追加做可能是錯在這裏golang中以下json數據的結構表示是什麼?

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Person struct { 
    ID  string `json:"id,omitempty"` 
    Firstname string `json:"firstname,omitempty"` 
    Lastname string `json:"lastname,omitempty"` 
    Address []Address `json:"address,omitempty"` 
} 

type Address[] struct { 
    City string `json:"city,omitempty"` 

} 


func main() { 

var people []Person 
people = append(people, Person{ID: "1", Firstname: "Nic", Lastname: "Raboy", Address: []Address{{City: "Dublin"},{ City: "CA"}}}) 
b, err := json.Marshal(people) 
    if err != nil { 
     fmt.Println("json err:", err) 
    } 
    fmt.Println(string(b)) 
} 

回答

0

這將是下面。這是使用優秀JSON-to-GO工具生成:

type MyStruct struct { 
    Devices []struct { 
     ID     int `json:"id"` 
     TargetIP    string `json:"targetIp"` 
     Iops     string `json:"iops"` 
     Capacity    int `json:"capacity"` 
     AllowedVirtualGuests []struct { 
      Name string `json:"Name"` 
     }       `json:"allowedVirtualGuests"` 
    }        `json:"devices"` 
} 

爲了簡化,雖然,你可以打破它成可讀性較小結構。示例如下:

package main 

import "fmt" 

type VirtualGuest struct { 
    Name string `json:"Name"` 
} 

type Device struct { 
    ID     int   `json:"id"` 
    TargetIP    string   `json:"targetIp"` 
    Iops     string   `json:"iops"` 
    Capacity    int   `json:"capacity"` 
    AllowedVirtualGuests []VirtualGuest `json:"allowedVirtualGuests"` 
} 

type MyStruct struct { 
    Devices []Device `json:"devices"` 
} 

func main() { 

    var myStruct MyStruct 

    // Add a MyStruct 
    myStruct.Devices = append(myStruct.Devices, Device{ 
     ID:1, 
     TargetIP:"1.2.3.4", 
     Iops:"iops", 
     Capacity:1, 
     AllowedVirtualGuests:[]VirtualGuest{ 
      VirtualGuest{ 
       Name:"guest 1", 
      }, 
      VirtualGuest{ 
       Name:"guest 2", 
      }, 
     }, 
    }) 

    fmt.Printf("MyStruct: %v\n", myStruct) 
} 
+0

非常感謝。我們可以通過將AllowedVirtualGuests字段定義爲[] struct而不是AllowedVirtualGuests [] VirtualGuest –

+0

應該能夠做到這一點。請參閱現有答案:http://stackoverflow.com/questions/32531854/how-to-initialize-nested-structure-array-in-golang – keno

0

你可以使用結構標籤一樣json:"id"的方式,請嘗試以下結構:

type Data struct { 
     Devices []struct { 
       Id     int `json:"id"` 
       IP     string `json:"targetIp"` 
       IOPS     string `json:"iops"` 
       Capacity    int `json:"capacity"` 
       AllowedVirtualGuests []struct { 
         Name string `json:"Name"` 
       } `json:"allowedVirtualGuests"` 
     } `json:"devices"` 
} 
+0

謝謝。但如何添加新的設備json數據? –

+0

將設備添加到結構中,然後封送它。 – zzn

+0

我們可以使用上面的代碼中使用的append方法做到這一點, –