zoukankan      html  css  js  c++  java
  • Go-json解码到结构体

    废话不多说,直接干就得了,上代码

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type IT struct {
    	Company  string   `json:"company"`  
    	Subjects []string `json:"subjects"`
    	IsOk     bool     `json:"isok"`
    	Price    float64  `json:"price"`
    }
    
    func main() {
    	jsonBuf := `
    	{
    		"company": "itcast",
    		"subjects": [
    			"Go",
    			"C++",
    			"Python",
    			"Test"
    		],
    		"isok": true,
    		"price": 666.666
    	}
    	`
    	var tmp IT
    	err := json.Unmarshal([]byte(jsonBuf), &tmp)
    	if err != nil {
    		fmt.Println("err=", err)
    		return
    	}
    	fmt.Println("tmp=", tmp) //tmp= {itcast [Go C++ Python Test] true 666.666}
    	
            //fmt.Printf("tmp=%+v
    ", tmp) //tmp={Company:itcast Subjects:[Go C++ Python Test] IsOk:true Price:666.666}
    	
    }
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type JsonServer struct {
    	ServerName string
    	ServerIP   string
    }
    
    type JsonServers struct {
    	Servers []JsonServer
    }
    
    func main() {
    	var s JsonServers
    	str := `{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
    	json.Unmarshal([]byte(str), &s)
    
    	fmt.Println(s)  //{[{Shanghai_VPN 127.0.0.1} {Beijing_VPN 127.0.0.2}]}
    }
    
    
  • 相关阅读:
    c语言之数据类型
    C语言之概述
    012.day12
    011.day011
    010.day010
    010.day08
    010.周六自习
    009.day07
    008.day06
    007.day05
  • 原文地址:https://www.cnblogs.com/Paul-watermelon/p/11210101.html
Copyright © 2011-2022 走看看