go从文件中读取json字符串并转换

go从文件中读取json字符串并转换

将要读取的文件的一部分

[
  {
    "children": [
      {
        "children": [
          {
            "code": 110118,
            "name": "密云区"
          },
          {
            "code": 110119,
            "name": "延庆区"
          }
        ],
        "code": 110000,
        "name": "北京市"
      }
    ],
    "code": "110000",
    "name": "北京市(京)"
  },
  {
    "children": [
      {
        "children": [

          {
            "code": 120118,
            "name": "静海区"
          },
          {
            "code": 120119,
            "name": "蓟州区"
          }
        ],
        "code": 120000,
        "name": "天津市"
      }
    ],
    "code": "120000",
    "name": "天津市(津)"
  },
  {
    "children": [
      {
        "code": 820000,
        "name": "澳门特别行政区(澳)"
      }
    ],
    "code": "820000",
    "name": "澳门特别行政区(澳)"
  },
  {
    "code": "710000",
    "name": "台湾省(台)"
  }
]
package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
	"encoding/json"
)

type County struct{	
	Code    int
	Name    string
}
type City struct {
	Children []County
	Code    int
	Name    string
}
type Province struct{
	Children []City
	Code    string
	Name    string
}

func main() {
	//打开文件
    inputFile, inputError := os.Open("xzqh.json")
    if inputError != nil {
        return
    }
    defer inputFile.Close()

	//按行读取文件
	var s string
    inputReader := bufio.NewReader(inputFile)
    for {
        inputString, readerError := inputReader.ReadString('\n')
        if readerError == io.EOF {
            break
        }
		s = s + inputString
    }
	fmt.Printf("all: \n%s", s)
	
	//json字符串转化为结构体
	fmt.Println("-------------------------------------------------")
	var province []Province
    if err := json.Unmarshal([]byte(s), &province); err == nil {
        fmt.Println(province)
		for i:=0;i<len(province);i++ {
			fmt.Println(province[i].Name);
		}
    }else{
		fmt.Println("转换失败")
	}
}

走过的坑:
1.接受json的字符串的结构体成员变量需要大写,否则无法解析

posted @ 2019-07-03 15:58  xcantaloupe  阅读(3894)  评论(0编辑  收藏  举报