我有以下json:
{
"app": {
"name": "name-of-app",
"version" 1
},
"items": [
{
"type": "type-of-item",
"inputs": {
"input1": "value1"
}
}
]
}
items[0].inputs
基于items[0].type
进行更改。知道这一点,有没有办法将
inputs
字段保留为字符串?这个想法是使用type
调用传递inputs
的正确处理程序,然后在其中使用正确的struct解析inputs
字符串。例:
package main
import (
"fmt"
"encoding/json"
)
type Configuration struct {
App App `json:"app"`
Items []Item `json:"items"`
}
type App struct {
Name string `json:"name"`
Version int `json:"version"`
}
type Item struct {
Type string `json:"type"`
// What to put here to mantain the field a string so I can Unmarshal later?
// Inputs string
}
var myJson = `
{
"app": {
"name": "name-of-app",
"version": 1
},
"items": [
{
"type": "type-of-item",
"inputs": {
"input1": "value1"
}
}
]
}
`
func main() {
data := Configuration{}
json.Unmarshal([]byte(myJson), &data)
fmt.Println("done!", data)
// Loop through data.Items and use the type to define what to call, and pass inputs
// as argument
}
先感谢您。
最佳答案
使用json.RawMessage来获取inputs
字段的原始JSON文本:
type Item struct {
Type string `json:"type"`
Inputs json.RawMessage
}
像这样使用它:
var data Configuration
if err := json.Unmarshal([]byte(myJson), &data); err != nil {
// handle error
}
// Loop over items and unmarshal items.Inputs to Go type specific
// to each input type.
for _, item := range data.Items {
switch item.Type {
case "type-of-item":
var v struct{ Input1 string }
if err := json.Unmarshal(item.Inputs, &v); err != nil {
// handle error
}
fmt.Printf("%s has value %+v\n", item.Type, v)
}
}
Run it on the playground。