我的结构不是编组到json中

时间:2013-03-16 16:58:12

标签: json go

我在Mac OS X 10.8.2上使用Go 1.0.3,我正在尝试使用json包,尝试将结构封送到json,但我一直空着{} json对象。

err值为nil,因此根据json.Marshal函数没有错误,并且结构是正确的。为什么会这样?

package main

import (
  "encoding/json"
  "fmt"
)

type Address struct {
  street string
  extended string
  city string
  state string
  zip string
}

type Name struct {
  first string
  middle string
  last string
}

type Person struct {
  name Name
  age int
  address Address
  phone string
}

func main() {
  myname := Name{"Alfred", "H", "Eigenface"}
  myaddr := Address{"42 Place Rd", "Unit 2i", "Placeton", "ST", "00921"}
  me := Person{myname, 24, myaddr, "000 555-0001"}

  b, err := json.Marshal(me)

  if err != nil {
    fmt.Println(err)
  }

  fmt.Println(string(b))    // err is nil, but b is empty, why?
  fmt.Println("\n")
  fmt.Println(me)           // me is as expected, full of data
}

3 个答案:

答案 0 :(得分:40)

您必须制作您想要公开的字段。 像这样:

type Address struct {
  Street string
  Extended string
  City string
  State string
  Zip string
}

errnil,因为所有导出的字段(在这种情况下都没有)都被正确编组。

工作示例:https://play.golang.org/p/9NH9Bog8_C6

查看文档http://godoc.org/encoding/json/#Marshal

答案 1 :(得分:5)

请注意,您还可以通过执行以下操作来操纵生成的JSON中字段的名称:

type Name struct {
  First string `json:"firstname"`
  Middle string `json:"middlename"`
  Last string `json:"lastname"` 
}

答案 2 :(得分:0)

JSON库无法查看结构中的字段,除非它们是公共的。就您而言,

// GroupJoin Fabrics with some of their OrderPlans:
var result = dbContext.Fabrics
    .GroupJoin(dbContext.OrderPlans.Where(orderPlan => ...)
    fabric => fabric.Id,              // from each Fabric take the primary key
    orderPlan => orderPlan.FabricId,  // from each OrderPlan take the foreign key

    // ResultSelector: take every Fabric with all his matching OrderPlans to make one new object:
    (fabric, orderPlansOfthisFabric) => new
    {
        // Select the Fabric properties you want
        Id = fabric.Id,
        Name = fabric.Name,
        Type = fabric.Type,

        OrderPlans = orderPlansOfThisFabric.Select(orderPlan => new
        {
             // Select the OrderPlan properties you want:
             Width = orderPlan.Width,
             Gsm = orderPlan.Gsm,
        }

        // Weight: calculate the sum of all OrderPlans of this Fabric:
        Weight = orderPlansOfThisFabric
                 .Select(orderPlan => orderPlan.Weight)
                 .Sum(),
    });

字段名称,年龄,地址和电话不是公开的(以小写字母开头)。在golang中,变量/函数以大写字母开头时是公共的。因此,要使其正常工作,您的结构需要看起来像这样:

type Person struct {
  name Name
  age int
  address Address
  phone string
}