简体   繁体   English

Golang:json.Unmarshal没有正确返回数据

[英]Golang: json.Unmarshal is not returning data correctly

I have a json file (themes/snow/theme.json) 我有一个json文件(themes / snow / theme.json)

{
    Name:'snow',
    Bgimage:'background.jpg',
    Width:600,
    Height:400,
    Itemrotation:'20,40',
    Text:{
        Fontsize:12,
        Color:'#ff00ff',
        Fontfamily:'verdana',
        Bottommargin:20
    },
    Decoration:[
        {
            Path:'abc.jpg',
            X:2,
            Y:4,
            Rotation:0
        },
        {
            Path:'def.png',
            X:4,
            Y:22,
            Rotation:10
        }
    ]
}

And I have a file that parse the json data 我有一个解析json数据的文件

package main

import (
    "fmt"
    "os"
    "encoding/json"
    "io/ioutil"
    "log"
)

const themeDirectory    = "themes"
const themeJsonFile     = "theme.json"

type TextInfo struct {
    Fontsize        int
    Color           string
    Fontfamily      string
    Bottommargin    int
}

type DecoInfo struct {
    Path            string
    X               int
    Y               int
    Rotation        int
}

type ThemeInfo struct {
    Name            string
    Bgimage         string
    Width           int
    Height          int
    Itemrotation    string
    Text            textInfo
    Decoration      []decoInfo
}

func main() {
    var tinfo = parseTheme("snow")
        //use tinfo to build graphics
}

func parseTheme(themename string) themeInfo {
    abspath, _ := os.Getwd()
    filename :=  abspath + "/" + themeDirectory + "/" + themename + "/" + themeJsonFile

    //Check this file exists
    if _, error := os.Stat(filename); error != nil {
        if os.IsNotExist(error) {
            log.Fatal(filename + " does not exist")
            os.Exit(1)
        }
    } 

    filebyte, error := ioutil.ReadFile(filename) 
    if error != nil { 
        log.Fatal("Could not read file " + filename + " to parse")
        os.Exit(1) 
    } 

    var t themeInfo
    json.Unmarshal(filebyte, &t) 
    fmt.Println(t)
    return t
}

You can see I have 2 lines before the end 你可以看到我在结束前有2行

 fmt.Println(t)

I am not sure why does it print 我不知道为什么打印

{  0 0  {0   0} []}

I expect it should return me themeInfo in a usable way, so that I can use it for further processing.What am I doing wrong here? 我希望它能以一种有用的方式返回我的themeInfo,这样我就可以用它来进一步处理。我在这里做错了什么?

As the json package uses reflection to dissect your structs, it can only see fields that are exported . 由于json包使用反射来剖析结构,因此它只能看到导出的字段。 All of your field names begin with lower case letters, therefore they are not exported. 所有字段名称都以小写字母开头,因此不会导出它们。 Change the names to start with upper case letters and I suspect it will start working for you. 将名称更改为以大写字母开头,我怀疑它将开始为您工作。

Your JSON is not valid. 您的JSON无效。 JavaScript allows single quotes; JavaScript允许单引号; JSON does not . JSON 没有 Further, the object keys must be double quoted: 此外,对象键必须双引号:

Valid:

{ "name": "Simon" }

Invalid:

{ name: "Simon" }
{ 'name': "Simon" }
{ "name": 'Simon' }

If you wrap your JSON keys and values with double quotes, you'll see the expected output: 如果用双引号包装JSON键和值,您将看到预期的输出:

{snow background.jpg 600 400 20,40 {12 #ff00ff verdana 20} [{abc.jpg 2 4 0} {def.png 4 22 10}]}

For exmaple, 例如,

const sampleTheme       = `{
    "Name":"snow",
    "Bgimage":"background.jpg",
    "Width":600,
    "Height":400,
    "Itemrotation":"20,40",
    "Text":{
        "Fontsize":12,
        "Color":"#ff00ff",
        "Fontfamily":"verdana",
        "Bottommargin":20
    },
    "Decoration":[
        {
            "Path":"abc.jpg",
            "X":2,
            "Y":4,
            "Rotation":0
        },
        {
            "Path":"def.png",
            "X":4,
            "Y":22,
            "Rotation":10
        }
    ]
}`

For the full program, see: http://play.golang.org/p/SLhaLbJcla 有关完整的计划,请参阅: http//play.golang.org/p/SLhaLbJcla

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM