2015-04-02 61 views
2

使用接口,我有一些JSON代碼,可以看起來像:與Golang地圖和結構和JSON

{ 
    "message_id": "12345", 
    "status_type": "ERROR", 
    "status": { 
     "x-value": "foo1234", 
     "y-value": "bar4321" 
    } 
} 

或可以是這樣的。正如你所看到的,根據status_type,「status」元素從字符串的標準對象變爲字符串數組的對象。

{ 
    "message_id": "12345", 
    "status_type": "VALID", 
    "status": { 
     "site-value": [ 
      "site1", 
      "site2" 
     ] 
    } 
} 

我想,我需要有我的「狀態」結構採取類似地圖的「地圖[字符串]接口{}」,但我不知道到底該怎麼做。

你可以在操場上看到代碼。
http://play.golang.org/p/wKowJu_lng

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type StatusType struct { 
    Id  string   `json:"message_id,omitempty"` 
    Status map[string]string `json:"status,omitempty"` 
} 

func main() { 
    var s StatusType 
    s.Id = "12345" 
    m := make(map[string]string) 
    s.Status = m 
    s.Status["x-value"] = "foo1234" 
    s.Status["y-value"] = "bar4321" 

    var data []byte 
    data, _ = json.MarshalIndent(s, "", " ") 

    fmt.Println(string(data)) 
} 

回答

4

我想通了,我想..

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type StatusType struct { 
    Id  string   `json:"message_id,omitempty"` 
    Status map[string]interface{} `json:"status,omitempty"` 
} 

func main() { 
    var s StatusType 
    s.Id = "12345" 
    m := make(map[string]interface{}) 
    s.Status = m 

    // Now this works 
    // s.Status["x-value"] = "foo1234" 
    // s.Status["y-value"] = "bar4321" 

    // And this works 
    sites := []string{"a", "b", "c", "d"} 
    s.Status["site-value"] = sites 

    var data []byte 
    data, _ = json.MarshalIndent(s, "", " ") 

    fmt.Println(string(data)) 
} 
+1

你可以嘗試延遲與RawMessage型狀態的解組。然後,根據status_type值對它進行解組。 – 2015-04-02 03:13:45

+0

你能舉個例子嗎? – jordan2175 2015-04-02 05:12:55

+0

inteface - >界面 – lhe 2016-03-23 03:49:00