Golang根据type解析json数据RawMessage
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
在程序中使用Json数据时,有时会根据type的类型不同,定义的data数据的json结构不同。
如:
{
"type":"File",
"object":{
"filename":"test"
}
}
{
"type":"Png",
"object":{
"width":1280,
"hight":1920
}
}
此时在解析json数据时,需要先解析出type的值,再根据type的值进行判断来解析object的数据。Golang提供了RawMessage来处理这种情况:
示例代码如下:
package main
import (
"encoding/json"
)
type UpLoadSomething struct {
Type string
Object interface{}
}
type File struct {
FileName string
}
type Png struct {
Width int
Hight int
}
func main() {
input :=
{
"type": "File",
"object": {
"filename": "for test"
}
}
var object json.RawMessage
ss := UpLoadSomething{
Object: &object,
}
if err := json.Unmarshal([]byte(input), &ss); err != nil {
panic(err)
}
switch ss.Type {
case "File":
var f File
if err := json.Unmarshal(object, &f); err != nil {
panic(err)
}
println(f.FileName)
case "Png":
var p Png
if err := json.Unmarshal(object, &p); err != nil {
panic(err)
}
println(p.Wide)
}
}
欢迎扫码关注公众号,更好的交流




适用于现代 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 天前
更多推荐
所有评论(0)