[gogf/gf]v1.12.1 版本继承结构体出错

2024-06-25 469 views
4

上次解决了https://github.com/gogf/gf/issues/571这个issue后,发现原有的继承结构体方式解析出错。

type BaseApiRsp struct {
    Ret int    `json:"ret"`
    Msg string `json:"msg"`
}

type DownlineAppidRsp struct {
    BaseApiRsp
}
var rsp DownlineAppidRsp

通过gjson.New(&rsp).MustToJsonString()反序列化的结果为

{
    "BaseApiRsp": {
        "ret": 0,
        "msg": "xxx"
    }
}

以前的版本期望的结果为

{
    "ret": 0,
    "msg": "xxx"
}

回答

3

补充一个例子

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gogf/gf/encoding/gjson"
)

type A struct{
    D string
    E string
}
type B struct{
    A
    F string
}

func SystemJsonEncode (a interface{}) string{
    js,err :=json.Marshal(a)
    if err!=nil{
        return "{}"
    }else{
        return fmt.Sprintf("%s",js)
    }
}

func main() {
    var b B
    fmt.Println(SystemJsonEncode(b))
    fmt.Println(gjson.New(b).MustToJsonString())
}

结果

{"D":"","E":"","F":""}
{"A":{"D":"","E":""},"F":""}
5

收到,我看看

7

@zmcity 感谢反馈,请使用master分支再试试。

6

这个修复方式会复现上次的issue,希望下面case的行为与"encoding/json"行为保持一致。

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gogf/gf/encoding/gjson"
)

type A struct{
    F string
    G string
}

type B struct{
    A
    H string
}

type C struct {
    A A
    F string
}

type D struct{
    I A
    F string
}

func SystemJsonEncode (a interface{}) string{
    js,err :=json.Marshal(a)
    if err!=nil{
        return "{}"
    }else{
        return fmt.Sprintf("%s",js)
    }
}

func main() {
    fmt.Println("encoding/json", SystemJsonEncode(B{}))
    fmt.Println("gjson", gjson.New(B{}).MustToJsonString())

    fmt.Println("encoding/json", SystemJsonEncode(C{}))
    fmt.Println("gjson", gjson.New(C{}).MustToJsonString())

    fmt.Println("encoding/json", SystemJsonEncode(D{}))
    fmt.Println("gjson", gjson.New(D{}).MustToJsonString())
}

输出结果

encoding/json {"F":"","G":"","H":""}
gjson {"F":"","G":"","H":""}
encoding/json {"A":{"F":"","G":""},"F":""}
gjson {"F":"","G":""}
encoding/json {"I":{"F":"","G":""},"F":""}
gjson {"F":"","G":""}
1

@zmcity 好的,我看看哈

5

@zmcity 感谢反馈,请更新到最新的master代码再试试。

9

非常感谢 经测试没有发现问题了