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

huangapple go评论90阅读模式
英文:

Golang: json.Unmarshal is not returning data correctly

问题

我有一个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
}
]
}

我有一个解析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")
//使用tinfo构建图形
}

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

//检查文件是否存在
if _, error := os.Stat(filename); error != nil {
    if os.IsNotExist(error) {
        log.Fatal(filename + "不存在")
        os.Exit(1)
    }
} 

filebyte, error := ioutil.ReadFile(filename) 
if error != nil { 
    log.Fatal("无法读取文件" + filename + "进行解析")
    os.Exit(1) 
} 

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

}

你可以看到在最后之前我有两行

fmt.Println(t)

我不确定为什么会打印出

{ 0 0 {0 0} []}

我期望它应该以可用的方式返回themeInfo,以便我可以用它进行进一步处理。我在这里做错了什么?

英文:

I have a json file (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

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

 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?

答案1

得分: 17

由于json包使用反射来解析您的结构体,它只能看到被导出的字段。您所有的字段名称都以小写字母开头,因此它们没有被导出。将这些名称改为以大写字母开头,我猜它会开始为您工作。

英文:

As the json package uses reflection to dissect your structs, it can only see fields that are exported. 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.

答案2

得分: 9

你的JSON不是有效的。JavaScript允许使用单引号;JSON不允许。此外,对象的键必须使用双引号括起来:

有效的示例:

{ "name": "Simon" }

无效的示例:

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

如果你用双引号包裹JSON的键和值,你将看到预期的输出:

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

例如,

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 } ] }

完整程序请参见:http://play.golang.org/p/SLhaLbJcla

英文:

Your JSON is not valid. JavaScript allows single quotes; JSON does not. 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:

{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

huangapple
  • 本文由 发表于 2012年9月19日 10:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/12487561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定