本文介绍了取消声音JSON嵌套结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同的json字节输入,我需要将其解组为一个嵌套的json结构。我能够将json解组到应用程序结构中。但是我无法添加到状态结构。

我试图解组,但这并不起作用,因为我的app1& app2是App类型而不是字节。并试图直接设置给出的错误不能使用app1(类型的应用程序)作为类型[]应用程序中的任务

  package main 

导入(
encoding / json
fmt
反映


类型App结构{
Appname字符串`json:appname`
构建字符串`json:builds`
}

类型状态struct {
Apps []应用程序``
}

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

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

//解组json数据到App
var app1 App
json.Unmarshal(jsonData1,& app1)

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

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

status.Apps = app1
status.Apps = app2

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


解决方案

不能将单个元素分配给数组字段,

  status.Apps = app1 
status.Apps = app2

类似于

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

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

另外,您的JSON字段名为 buildconfigs ,并且在结构规范 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))
}
解决方案

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

这篇关于取消声音JSON嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:39