3

Go实践之JSON解析

 2 years ago
source link: http://kangkona.github.io/json-and-go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go实践之JSON解析

28/Nov 2014

Go

当我们开发了一个新版本的软件时,通常需要和稳定版进行对比,进行QoS评估。对实时性网络服务而言,比较客观的做法是同时请求相同的服务,然后对比返回结果。

首先,我们对一些常用的函数进行包裹,简化操作:

发送Http请求

func sendHttpRequest(url string) string {
	response, _ := http.Get(url)
	defer response.Body.Close()
	var bodystr string
             if response.StatusCode == 200 {
             	body, _ := ioutil.ReadAll(response.Body)
             	bodystr = string(body)
             } else {
                          return ""
             }
             return bodystr
}

获取Json数据

如果你知道返回的json数据的格式,可以事先定义好对应的数据结构。例如json返回内容为

{
  "name":"Monica",
  "age": 10, 
  "hobby" : ["music", "dance"]
}

对应的数据结构和操作:

type Person struct {
  name string `json:"name"`
  age string `json:"age"`
  hobby []string `json:"hobby"`
}

bodystr := sendHttpRequest(url)

var person Person
err := json.Unmarshal([]byte(bodystr), &person)

这样json内容就会变成一个实例化的Person对象,所有的json成员都会对应类型化。

如果我们不知道json数据格式怎么办? json的最外层肯定是一个map, 所以可以把json数据反序列化为一个通用的 interface{} :

func getJson(url string) map[string]interface{} {
	bodystr := sendHttpRequest(url)
        var  object interface{}
        err := json.Unmarshal([]byte(bodystr), &object)
	if err != nil {
	      return nil	
	} else {
	      return object.(map[string]interface{})
	}
}

好处是通用,可以解析任意的json,但由于不知内层数据的类型,因此只作了最外层map的解析,返回数据的类型为map[string]interface{}。之后可能会根据需要进行类型断言,转换等。

感觉json目前已经成了网络数据传输格式的事实标准,有很多人总结过JSON与XML的区别比较,我觉得json最大的优势是:程序员友好。json中的map, array, set, string, num都能完美地对应到某一编程语言中,即表示的不仅仅是文本,还是带类型的数据。而xml本质还是文本,要借助于xslt,scheme,属性等一堆东西实现json的类型化,表示成本高,解析成本也高。可能的好处是比较体系化,有成套的解决方案,用户可视化方便。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK