• go-json处理的问题


    1、通过Decoder来解析json串

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"io"
    	"log"
    	"strings"
    )
    
    func main() {
    	const jsonStream = `
    	{"Name":"Ed","Text":"Knock knock."}
    	{"Name":"Sam","Text":"Who's there?"}
    	`
    	type Message struct {
    		Name, Text string
    	}
    
    	dec := json.NewDecoder(strings.NewReader(jsonStream))
    	for {
    		var m Message
    		if err := dec.Decode(&m); err == io.EOF {
    			break
    		} else if err != nil {
    			log.Fatal(err)
    		}
    		fmt.Printf("%s:%s
    ", m.Name, m.Text)
    	}
    }
    //output
    //Ed:Knock knock.
    //Sam:Who's there?
    

    2、marshal对struct进行json字符串化

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    )
    
    func main() {
    	type ColorGroup struct {
    		ID     int
    		Name   string
    		Colors []string
    	}
    	group := ColorGroup{
    		ID:     1,
    		Name:   "Reds",
    		Colors: []string{"Crimson", "Red", "Ruby", "Marroon"},
    	}
    	b, err := json.Marshal(group)
    	if err != nil {
    		fmt.Println("err:", err)
    	}
    	os.Stdout.Write(b)
    }
    //output
    //{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Marroon"]}
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type Color struct {
    	Red string `json:"r"` //json中key是r
    	Yel string `json:"yel,omitempty"`//json中key是yel,omitempty表示当Yel为空时,json中不输出
    	Blue string `json:"-"`//json序列化是忽略
    	Age string `json:",-"`//json序列化时使用默认的Age key,
    	name string `json:"name"`//小写的名字json序列化忽略,私有成员变量,json包无法访问
    }
    
    func main()  {
    	color := Color{
    		Red:"256",
    		Yel:"20",
    		Blue:"10",
    		Age:"10",
    		name:"chen",
    	}
    	bs,_ := json.Marshal(color)
    	fmt.Printf("%s
    ",bs)
    }
    
    //{"r":"256","yel":"20","Age":"10"}
    

    3、Unmarshal 解析json

    json规范中,没有区分整数和浮点数

    json数据结构

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    //指定反解析的json struct类型。 fansCount会转换为int64类型。不会有精度的丢失。
    type User struct {
    	Name string
    	FansCount int64
    }
    
    func main()  {
    	const jsonStream = `
            {"name":"ethancai", "fansCount": 9223372036854775807}`
            var user User
            err := json.Unmarshal([]byte(jsonStream),&user)
            if err != nil {
            	fmt.Println("error:",err)
    		}
    		fmt.Printf("%+v 
    ",user)
    }
    
    //{Name:ethancai FansCount:9223372036854775807}
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"reflect"
    )
    
    func main()  {
    	const jsonStream = `{"name":"ethancai", "fansCount": 9223372036854775807}`
    	var user interface{} //不指定反序列化的类型,
    	err := json.Unmarshal([]byte(jsonStream),&user)
    	if err != nil {
    		fmt.Println("err",err)
    	}
    	m := user.(map[string]interface{})
    
    	fansCount := m["fansCount"] //没有类型,反序列化时会默认转换为float64,如果整数过大,会丢失精度
    	fmt.Printf("%+v
    ",reflect.TypeOf(fansCount).Name())
    	fmt.Printf("%+v
    ",fansCount.(float64))
    }
    //float64
    //9.223372036854776e+18
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type User struct {
    	Name string
    	FansCount interface{} //不指定变量类型
    }
    func main()  {
    	const jsonStream = `{"name":"ethancai", "fansCount": 9223372036854775807}`
    	var user User
    	err := json.Unmarshal([]byte(jsonStream),&user)
    	if err != nil {
    		fmt.Println("err",err)
    	}
    	fmt.Printf("%+v 
    ",user)
    }
    //{Name:ethancai FansCount:9.223372036854776e+18}
    

    为了解决精度丢失的问题,需要引入json.Number类型

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type User struct {
    	Name string
    	FansCount json.Number //使用json.Number类型,本质是string类型。不会有精度丢失
    }
    func main()  {
    	const jsonStream = `{"name":"ethancai", "fansCount": 9223372036854775807}`
    	var user User
    	err := json.Unmarshal([]byte(jsonStream),&user)
    	if err != nil {
    		fmt.Println("err",err)
    	}
    	fmt.Printf("%+v 
    ",user)
    	num ,_ := user.FansCount.Int64() //然后转换成想要的类型
    	fmt.Println(num)
    }
    //{Name:ethancai FansCount:9223372036854775807}
    //9223372036854775807
    
  • 相关阅读:
    【iPhone开发】说说Xcode4中xib绑定的原理转
    转 IOS下的图片
    免证书调试Iphone程序(转)
    牛B的Python模块(转)
    6 个手机开发方面很有用的应用
    留个脚印!
    Android初学者入门PDF版
    IOS下的MVC
    android2.2源码编译-Ubuntu10.04 (X86) + android2.2 + JDK1.6
    10 款 Windows 下最佳的免费 PHP 编辑器
  • 原文地址:https://www.cnblogs.com/promenader/p/9878933.html
Copyright © 2020-2023  润新知