【问题标题】:JSON Marshalling losing struct referenceJSON编组丢失结构引用
【发布时间】:2022-01-02 10:35:58
【问题描述】:

我正在研究一个关于编组的示例,并决定巧妙地使用它。希望我可以传递一个类似于json.Unmarshall 函数的通用接口引用,并通过输入而不是重复相同的代码来处理我的其他测试用例(是的,我来自Java)。相反,我得到了一个地图而不是一个结构。看来我也没有办法向下暗示这种结构的“类型”是什么。
问题:

  1. 我怎样才能找回适当的结构类型?
  2. 采用这种实用方法的方法是否合理?

代码:
    //test 1 - simple dto
    var country models.Country
    var outCountry, errorCountry = attemptParse("Simple DTO", "./json/country.json", country)
    fmt.Println("Return - ", outCountry, " - ", errorCountry)
...
func attemptParse(test string, dataFile string, v interface{}) (interface{}, error){

    ...
    err := json.Unmarshal(data, &v)
    if err != nil {
        fmt.Println("Test - ", test, " - fail", err)
        return nil, err
    }

    fmt.Println("Test - ", test, " - result:")
    fmt.Println(v)
    return v, nil
}

还尝试编组到nptr := reflect.New(reflect.TypeOf(v)),但这以我无法解析的地址结束。
输出:

Test -  Simple DTO  - start
Test -  Simple DTO  - result:
map[Capital:Washington DC Continent:North America Name:USA]
Return -  map[Capital:Washington DC Continent:North America Name:USA]  -  <nil>

【问题讨论】:

标签: go


【解决方案1】:
  1. 尝试将指针传递给attemptParse() 函数:

    var outCountry, errorCountry = attemptParse("Simple DTO", "./json/country.json", &country)
    

    改变

    err := json.Unmarshal(data, &v)
    

    err := json.Unmarshal(data, v)
    

    请查看此游乐场了解更多详情:https://go.dev/play/p/XEN5cZce0tG

  2. 我不确定您到底要测试什么。但我宁愿先尝试表驱动测试:https://dave.cheney.net/2019/05/07/prefer-table-driven-tests

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多