栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Go-解码JSON,因为它仍通过net / http流进

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go-解码JSON,因为它仍通过net / http流进

使用可以解码JSON流

json.Deprer

使用

Deprer.Depre()
,我们可以读取(解组)单个值,而不会消耗和解组整个流。这很酷,但是您的输入是一个“单个”
JSON对象,而不是一系列JSON对象,这意味着对的调用
Deprer.Depre()
将尝试解组所有项目(大对象)的完整JSON对象。

我们想要的是部分地,即时地处理单个JSON对象。为此,我们可以使用

Deprer.Token()
哪个仅解析(高级)JSON输入流中的下一个后续令牌并返回它。这称为
事件驱动的 解析。

当然,我们必须“处理”(解释并对其执行操作)令牌,并构建一个“状态机”,以跟踪我们在处理的JSON结构中的位置。

这是解决您问题的实现。

我们将使用以下JSON输入:

{    "somefield": "value",    "otherfield": "othervalue",    "items": [        { "id": "1", "data": "data1" },        { "id": "2", "data": "data2" },        { "id": "3", "data": "data3" },        { "id": "4", "data": "data4" }    ]}

并阅读

items
,用这种类型建模的“大对象”:

type LargeObject struct {    Id   string `json:"id"`    Data string `json:"data"`}

我们还将解析和解释JSON对象中的其他字段,但是我们只会记录/打印它们。

为了简便起见,我们将使用以下辅助错误处理函数:

he := func(err error) {    if err != nil {        log.Fatal(err)    }}

现在让我们看一下操作。为了简洁起见,并在Go
Playground上进行了有效的演示,在下面的示例中,我们将从

string
值中读取。要读取实际的HTTP响应正文,我们只需要更改一行,这就是我们创建方式
json.Deprer

dec := json.NewDeprer(res.Body)

因此,演示:

dec := json.NewDeprer(strings.NewReader(jsonStream))// We expect an objectt, err := dec.Token()he(err)if delim, ok := t.(json.Delim); !ok || delim != '{' {    log.Fatal("Expected object")}// Read propsfor dec.More() {    t, err = dec.Token()    he(err)    prop := t.(string)    if t != "items" {        var v interface{}        he(dec.Depre(&v))        log.Printf("Property '%s' = %v", prop, v)        continue    }    // It's the "items". We expect it to be an array    t, err := dec.Token()    he(err)    if delim, ok := t.(json.Delim); !ok || delim != '[' {        log.Fatal("Expected array")    }    // Read items (large objects)    for dec.More() {        // Read next item (large object)        lo := LargeObject{}        he(dec.Depre(&lo))        fmt.Printf("Item: %+vn", lo)    }    // Array closing delim    t, err = dec.Token()    he(err)    if delim, ok := t.(json.Delim); !ok || delim != ']' {        log.Fatal("Expected array closing")    }}// Object closing delimt, err = dec.Token()he(err)if delim, ok := t.(json.Delim); !ok || delim != '}' {    log.Fatal("Expected object closing")}

这将产生以下输出:

2009/11/10 23:00:00 Property 'somefield' = value2009/11/10 23:00:00 Property 'otherfield' = othervalueItem: {Id:1 data:data1}Item: {Id:2 data:data2}Item: {Id:3 data:data3}Item: {Id:4 data:data4}

在Go Playground上尝试完整的工作示例。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/471112.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号