dquv73115 2016-03-31 23:43
浏览 63
已采纳

将JSON解组为嵌套结构

I have different json byte inputs that I need to unmarshal into a nested json structure. I am able to unmarshal the json into the struct App. However I am unable to add to "status" struct.

I tried to unmarshal, but that doesnt work since my app1 & app2 are of type App instead of bytes. And trying to set directly gives the error "cannot use app1 (type App) as type []App in assignment"

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type App struct {
    Appname string `json:"appname"`
    Builds  string `json:"builds"`
}

type Status struct {
    Apps []App `json:"apps"`
}

func main() {
    jsonData1 := []byte(`
            {  
               "appname": "php1",
               "buildconfigs":"deleted"
            }
        `)

    jsonData2 := []byte(`
            {  
               "appname": "php2",
               "buildconfigs":"exists"
            }
        `)

    // unmarshal json data to App
    var app1 App
    json.Unmarshal(jsonData1, &app1)

    var app2 App
    json.Unmarshal(jsonData2, &app2)

    var status Status
    //json.Unmarshal(app1, &status)
    //json.Unmarshal(app2, &status)

    status.Apps = app1
    status.Apps = app2

    fmt.Println(reflect.TypeOf(app1))
    fmt.Println(reflect.TypeOf(app1))
}

展开全部

  • 写回答

2条回答 默认 最新

  • dousao6313 2016-04-01 00:22
    关注

    You can't assign single element to array field so convert your

    status.Apps = app1
    status.Apps = app2
    

    to something like

    status.Apps = []App{app1, app2}
    

    or

    status.Apps = []App{}
    status.Apps = append(status.Apps, app1)
    status.Apps = append(status.Apps, app2)
    

    Also your JSON field named buildconfigs and in struct specification json:"builds". Structure's field always will be empty in this case.

    Working example http://play.golang.org/p/fQ-XQsgK3j

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部