2015-04-02 64 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