dongwei4096
2015-11-25 08:33
浏览 280

GoLang Struct到JSON不转换

This question already has an answer here:

I am trying to convert my struct "Sim" into JSON, after being filled with data.

When I print the var s, it shows correct information, when I print data, it shows blank.

How do I convert Struct to JSON?

Reduced Code Below:

type Sim struct {
    yr, ag, av, db, wd, st []int
    withdrawal []string
}

func main() {
    // Creating simulation
    var s Sim

    // Filling with data
    s = simulate(15000, 60, 65, 90, 2015, 10.0, 140000.0, true, s)

    // Converting to JSON, for transmission over web
    data, err := json.Marshal(s)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Data is correct
    fmt.Println(s)

    // Prints: {}
    fmt.Println(string(data))
}
</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案

  • 为什么Golang不能从具有小写字母的结构生成json? \ r 1个答案

    我正在尝试转换我的

    当我打印var s时,它显示正确的信息,当我打印数据时,它显示为空白。 \ n

    如何将Struct转换为JSON?

    以下简化的代码:

      type Sim struct {
     yr  ,ag,av,db,wd,st [] int 
    退出[] string 
    } 
     
    func main(){
     //创建模拟
     var s Sim 
     
     // Fi 用数据填充
    s = Simulation(15000,60,65,90,2015,10.0,140000.0,true,s)
     
     //转换为JSON,以通过Web传输数据,err:= json.Marshal  (s)
     if err!= nil {
     fmt.Println(err)
     return 
    } 
     
     //数据正确
     fmt.Println(s)
     
     //打印:  {} 
     fmt.Println(string(data))
    } 
       
     
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drbl91357 2015-11-25 08:41
    已采纳

    Fields in your structures starts with lower case so they are not marshalled to JSON. Make them start with upper case letter.

    package main
    
    import "encoding/json"
    import "fmt"
    
    type Sim struct {
        Yr, Ag, Av, Db, Wd, St []int
        Withdrawal             []string
    }
    
    func main() {
        // Creating simulation
        var s Sim
    
        // Converting to JSON, for transmission over web
        data, err := json.Marshal(s)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        // Data is correct
        fmt.Println(s)
    
        // Prints: {}
        fmt.Println(string(data))
    }
    

    Playground

    JSON serialization in GO

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题