Go-json解码到接口及根据键获取值

Go-json解码到接口及根据键获取值

package mainimport ("encoding/json""fmt""github.com/bitly/go-simplejson"
)type JsonServer struct {ServerName stringServerIP   string
}type JsonServers struct {Servers []JsonServer
}func main() {var s JsonServersstr := `{"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}]}b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)var f interface{}json.Unmarshal(b, &f)fmt.Printf("%+v\n", f) // map[Name:Wednesday Age:6 Parents:[Gomez Morticia]]m := f.(map[string]interface{})for k, v := range m {switch vv := v.(type) {case string:fmt.Println(k, "is string", vv) //Name is string Wednesdaycase int:fmt.Println(k, "is int", vv)case float64:fmt.Println(k, "is float64", vv) //Age is float64 6case []interface{}:fmt.Println(k, "is an array:") //Parents is an array://0 Gomez//1 Morticiafor i, u := range vv {fmt.Println(i, u)}default:fmt.Println(k, "is of a type I don't know how to handle")}}/**如您所见,我们现在可以通过interface{}解析未知格式的JSON并键入断言。以上示例是官方解决方案,但类型断言并不总是方便。因此,我推荐一个名为simplejson的开源项目,由bitly创建和维护。以下是如何使用此项目处理未知格式的JSON的示例:go get ithub.com/bitly/go-simplejson*/// 根据键获取值js, err := simplejson.NewJson([]byte(`{"test": {"array": [1, "2", 3],"int": 10,"float": 5.150,"bignum": 9223372036854775807,"string": "simplejson","bool": true}
}`))if err != nil {fmt.Println("err:", err)}arr, _ := js.Get("test").Get("array").Array() //arr: [1 2 3]fmt.Println("arr:", arr)i, _ := js.Get("test").Get("int").Int() //i: 10fmt.Println("i:", i)ms := js.Get("test").Get("string").MustString() //ms: simplejsonfmt.Println("ms:", ms)
}

json解码到接口

package mainimport ("encoding/json""fmt"
)func main() {jsonBuf := `{"company": "itcast","subjects": ["Go","C++","Python","Test"],"isok": true,"price": 666.666}`//创建一个mapm := make(map[string]interface{}, 4)err := json.Unmarshal([]byte(jsonBuf), &m)if err != nil {fmt.Println("err=", err)return}fmt.Println("m=", m)     //m= map[company:itcast subjects:[Go C++ Python Test] isok:true price:666.666]fmt.Printf("m=%+v\n", m) //m=map[isok:true price:666.666 company:itcast subjects:[Go C++ Python Test]]var s strings = m["company"].(string)fmt.Println("s= ", s) //s=  itcastvar s1 bools1 = m["isok"].(bool)fmt.Println("s1= ", s1) //s1=  truevar s2 float64s2 = m["price"].(float64)fmt.Println("s2= ", s2) //s2=  666.666var str string//类型断言for key, value := range m {// fmt.Printf("%v===>%v\n", key, value)switch data := value.(type) {case string:str = datafmt.Printf("map[%s]的值类型为string,内容为%s\n", key, str)case bool:fmt.Printf("map[%s]的值类型为bool,内容为%v\n", key, data)case float64:fmt.Printf("map[%s]的值类型为float64,内容为%v\n", key, data)case []string:fmt.Printf("map[%s]的值类型为[]stiring1,内容为%v\n", key, data)case []interface{}:fmt.Printf("map[%s]的值类型为[]stiring2,内容为%v\n", key, data)}/*map[company]的值类型为string,内容为itcastmap[subjects]的值类型为[]stiring2,内容为[Go C++ Python Test]map[isok]的值类型为bool,内容为truemap[price]的值类型为float64,内容为666.666*/}
}

转载于:https://www.cnblogs.com/Paul-watermelon/p/11210526.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392446.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#接口的显隐实现

显示接口实现与隐式接口实现 何为显式接口实现、隐式接口实现?简单概括,使用接口名作为方法名的前缀,这称为“显式接口实现”;传统的实现方式,称为“隐式接口实现”。下面给个例子。 IChineseGreeting接口,…

亚马逊 各国站点 链接_使用Amazon S3和HTTPS的简单站点托管

亚马逊 各国站点 链接by Georgia Nola乔治亚诺拉(Georgia Nola) 使用Amazon S3和HTTPS的简单站点托管 (Simple site hosting with Amazon S3 and HTTPS) Hiya folks!大家好! In this tutorial I’ll show you how to host a static website with HTTPS on AWS wit…

leetcode 387. 字符串中的第一个唯一字符(hash)

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 示例: s “leetcode” 返回 0 s “loveleetcode” 返回 2 class Solution { public int firstUniqChar(String s) { int[][] tempnew i…

marlin 三角洲_三角洲湖泊和数据湖泊-入门

marlin 三角洲Data lakes are becoming adopted in more and more companies seeking for efficient storage of their assets. The theory behind it is quite simple, in contrast to the industry standard data warehouse. To conclude this this post explains the logica…

tomcat中设置Java 客户端程序的http(https)访问代理

1、假定http/https代理服务器为 127.0.0.1 端口为8118 2、在tomcat/bin/catalina.sh脚本文件中设置JAVA_OPTS,如下图: 保存后重启tomcat就能生效。转载于:https://www.cnblogs.com/zhangmingcheng/p/11211776.html

java界面中显示图片_java中怎样在界面中显示图片?

方法一:JLabel helloLabel new JLabel("New label");helloLabel.setIcon(new ImageIcon("E:\\javaSE\u4EE3\u7801\\TimeManager\\asset\\hello.gif"));helloLabel.setBackground(Color.BLACK);helloLabel.setBounds(0, 0, 105, 50);contentPan…

one-of-k 编码算法_我们如何教K-12学生如何编码

one-of-k 编码算法by Christopher George克里斯托弗乔治(Christopher George) 我们如何教K-12学生如何编码 (How we’re teaching K-12 students how to code) Hello World! (Sorry, I couldn’t resist.) My name is Christopher George and I am currently a Junior at Carn…

knime简介_KNIME简介

knime简介Data Science is abounding. It considers different realms of the data world including its preparation, cleaning, modeling, and whatnot. To be precise, it is massive in terms of the span it covers and the opportunities it offers. Needless to say, th…

hadoop2.x HDFS快照介绍

说明:由于近期正好在研究hadoop的快照机制。看官网上的文档讲的非常仔细。就顺手翻译了。也没有去深究一些名词的标准译法,所以可能有些翻译和使用方法不是非常正确,莫要介意~~ 原文地址:(Apache hadoop的官方文档&…

MQTT服务器搭建--Mosquitto用户名密码配置

前言: 基于Mosquitto服务器已经搭建成功,大部分都是采用默认的是允许匿名用户登录模式,正式上线的系统需要进行用户认证。 1.用户参数说明 Mosquitto服务器的配置文件为/etc/mosquitto/mosquitto.conf,关于用户认证的方式和读取的…

java number string_java基础系列(一):Number,Character和String类及操作

这篇文章总结了Java中最基础的类以及常用的方法,主要有:Number,Character,String。1、Number类在实际开发的过程中,常常会用到需要使用对象而不是内置的数据类型的情形。所以,java语言为每个内置数据类型都…

谁参加了JavaScript 2018状况调查?

by Sacha Greif由Sacha Greif 谁参加了JavaScript 2018状况调查? (Who Took the State of JavaScript 2018 Survey?) 我们如何努力使调查更具代表性 (How we’re working to make the survey more representative) I was recently listening to a podcast episode…

机器学习 建立模型_建立生产的机器学习系统

机器学习 建立模型When businesses plan to start incorporating machine learning to enhance their solutions, they more often than not think that it is mostly about algorithms and analytics. Most of the blogs/training on the matter also only talk about taking …

CDH使用秘籍(一):Cloudera Manager和Managed Service的数据库

背景从业务发展需求,大数据平台须要使用spark作为机器学习、数据挖掘、实时计算等工作,所以决定使用Cloudera Manager5.2.0版本号和CDH5。曾经搭建过Cloudera Manager4.8.2和CDH4,在搭建Cloudera Manager5.2.0版本号的时候,发现对…

leetcode 455. 分发饼干(贪心算法)

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j]…

压缩/批量压缩/合并js文件

写在前面 如果文件少的话,直接去网站转化一下就行。 http://tool.oschina.net/jscompress?type3 1.压缩单个js文件 cnpm install uglify-js -g 安装 1>压缩单个js文件打开cmd,目录引到当前文件夹,cduglifyjs inet.js -o inet-min.js 或者 uglifyjs i…

angular依赖注入_Angular依赖注入简介

angular依赖注入by Neeraj Dana由Neeraj Dana In this article, we will see how the dependency injection of Angular works internally. Suppose we have a component named appcomponent which has a basic and simple structure as follows:在本文中,我们将看…

leetcode 85. 最大矩形(dp)

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。 示例 1: 输入:matrix [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“…

如何查看系统版本

1. winR,输入cmd,确定,打开命令窗口,输入msinfo32,注意要在英文状态下输入,回车。然后在弹出的窗口中就可以看到系统的具体版本号了。 2.winR,输入cmd,确定,打开命令窗口,输入ver&am…

java activemq jmx_通过JMX 获取Activemq 队列信息

首先在 activemq.xml 中新增以下属性在broker 节点新增属性 useJmx"true"在managementContext 节点配置断开与访问服务iP配置成功后启动下面来看测试代码/*** Title: ActivemqTest.java* Package activemq* Description: TODO(用一句话描述该文件做什么)* author LYL…