2013-02-18 54 views
2

我有很简单的测试:http://play.golang.org/p/wY4sN9AUky。配置从JSON解析,第一个字符串值解析好了,但第二个解析为空字符串,但它不是。转:JSON值未解析?

type Config struct { 
    Address  string "address" 
    Debug  bool "debug" 
    DbUrl  string "dburl" 
    GoogleApiKey string "google_api_key" 
} 

func (cfg *Config) read(json_code string) { 
    if e := json.Unmarshal([]byte(json_code), cfg); e != nil { 
     log.Printf("ERROR JSON decode: %v", e) 
    } 
} 

func main() { 
    var config Config 
    config.read(`{ 
    "address": "10.0.0.2:8080", 
    "debug": true, 
    "dburl": "localhost", 
    "google_api_key": "the-key" 
}`) 
    log.Printf("api key %s", config.GoogleApiKey) // <- empty string. why? 
    log.Printf("address %v", config.Address) 
} 

回答

4

您在结构中错误地指定了您的JSON名称。

GoogleApiKey string "google_api_key" 

应该

GoogleApiKey string `json:"google_api_key"` 

的JSON包会在文本中的json头。反引号分隔了一个原始字符串,它允许我们在google_api_key附近引用引号。

http://play.golang.org/p/KNxYhzGLAp

package main 

import (
    "log" 
    "encoding/json" 
) 

type Config struct { 
    Address string `json:"address"` 
    Debug bool `json:"debug"` 
    DbUrl string `json:"dburl"` 
    GoogleApiKey string `json:"google_api_key"` 
} 

func (cfg *Config) read(json_code string) { 
    if e := json.Unmarshal([]byte(json_code), cfg); e != nil { 
    log.Printf("ERROR JSON decode: %v", e) 
    } 
} 

func main() { 
    var config Config 
    config.read(`{ 
    "address": "10.0.0.2:8080", 
    "debug": true, 
    "dburl": "localhost", 
    "google_api_key": "the-key" 
}`) 
    log.Printf("api key %s", config.GoogleApiKey) 
    log.Printf("address %v", config.Address) 
} 
+3

只有真正需要的'JSON: “google_api_key”'。其他人映射到小写版本。 http://play.golang.org/p/QYLBUINktx – 2013-02-18 05:15:59