很多情况下我们需要判断json里面的一个字段,然后根据这个字段的类型,进行解析下面的字段类型,我们则使用json.RawMessage

 

 

package main

import (
	"encoding/json"
	"fmt"
)

type TestStruct struct {

	Type int
	Body json.RawMessage
}

type Person struct {
	Name string
	Age int
}


type Worker struct {

	Name string
    Job string
}


func main(){
    input := `
       {
        "Type": 1,
        "Body":{ 
            "Name":"ff",
            "Age" : 19
         }
    }`

    ts := TestStruct{}

	if  err := json.Unmarshal([]byte(input), &ts); err!= nil {
		panic( err)
	}

	switch  ts.Type {
	case 1:
		var p Person
		if err := json.Unmarshal(ts.Body, &p); err != nil {
			panic(err)
		}
		fmt.Println(p)
	case 2:
		var w Worker
		if err := json.Unmarshal(ts.Body, &w); err != nil {
			panic(err)
		}
		fmt.Println(w)
	}

}

 

GitHub 加速计划 / js / json
39
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6 binary -> binary_t Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 22 天前
f3dc4684 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 28 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐