GO JsonStr 2 obj

//project main.go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	fmt.Println(help())
	b := []byte(`{
					"Title": "Go语言编程",
					"Authors": ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"],
					"Publisher": "ituring.com.cn",
					"IsPublished": true,
					"Price": 9.99,
					"Sales": 1000000
				 }`)
	var r interface{}
	err := json.Unmarshal(b, &r)
	fmt.Println("r = ", r, "err = ", err, "\n")
	gobook, ok := r.(map[string]interface{})
	if ok {
		for k, v := range gobook {
			switch v2 := v.(type) {
			case string:
				fmt.Println(k, "is string", v2)
			case int:
				fmt.Println(k, "is int", v2)
			case bool:
				fmt.Println(k, "is bool", v2)
			case []interface{}:
				fmt.Println(k, "is an array:")
				for i, iv := range v2 {
					fmt.Println(i, iv)
				}
			default:
				fmt.Println(k, "is another type not handle yet")
			}
		}
	}
}

func help() string {
	return `
	Go内建这样灵活的类型系统,向我们传达了一个很有价值的信息:空接口是通用类型。如
	果要解码一段未知结构的JSON,只需将这段JSON数据解码输出到一个空接口即可。在解码JSON
	数据的过程中, JSON数据里边的元素类型将做如下转换:
 	JSON中的布尔值将会转换为Go中的bool类型;
 	数值会被转换为Go中的float64类型;
 	字符串转换后还是string类型;
 	JSON数组会转换为[]interface{}类型;
 	JSON对象会转换为map[string]interface{}类型;
 	null值会转换为nil
	`
}

输出:


	Go内建这样灵活的类型系统,向我们传达了一个很有价值的信息:空接口是通用类型。如
	果要解码一段未知结构的JSON,只需将这段JSON数据解码输出到一个空接口即可。在解码JSON
	数据的过程中, JSON数据里边的元素类型将做如下转换:
 	JSON中的布尔值将会转换为Go中的bool类型;
 	数值会被转换为Go中的float64类型;
 	字符串转换后还是string类型;
 	JSON数组会转换为[]interface{}类型;
 	JSON对象会转换为map[string]interface{}类型;
 	null值会转换为nil
	
r =  map[IsPublished:true Price:9.99 Sales:1e+06 Title:Go语言编程 Authors:[XuShiwei HughLv Pandaman GuaguaSong HanTuo BertYuan XuDaoli] Publisher:ituring.com.cn] err =  <nil> 

Title is string Go语言编程
Authors is an array:
0 XuShiwei
1 HughLv
2 Pandaman
3 GuaguaSong
4 HanTuo
5 BertYuan
6 XuDaoli
Publisher is string ituring.com.cn
IsPublished is bool true
Price is another type not handle yet
Sales is another type not handle yet

 

转载于:https://my.oschina.net/tsh/blog/896964

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值