dquv73115 2016-04-01 07: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 08: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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?