简体   繁体   English

Golang 动态解组 JSON

[英]Golang Dynamically Unmarshalling JSON

Is it possible in Go, given the below function, to unmarshall jsonString without knowing the type of c at runtime?给定下面的函数,在 Go 中是否有可能在不知道运行时c的类型的情况下解组jsonString

func findChargedItems(fs financialService, conditions []string) ([]*models.ChargedItem, error) {
    var jsonResult []string

    f := getChargedItemsQuery(conditions)
    q, _, _ := f.ToSql()

    err := fs.db.Select(&jsonResult, q)
    if err != nil {
        return nil, err
    }

    jsonString := fmt.Sprintf("[%v]", strings.Join(jsonResult, ","))
    c := make([]*models.ChargedItem, 0)
    err = json.Unmarshal([]byte(jsonString), &c)
    if err != nil {
        return nil, err
    }

    return c, nil
}

The problem is that I have tons of models that need to do this exact process and I'm repeating myself in order to achieve this.问题是我有大量模型需要执行这个确切的过程,我正在重复自己以实现这一目标。 I would like to just have a "generic" function findEntities that operates agnostic of ChargedItem and getChargedItemsQuery .我只想拥有一个“通用”函数findEntities ,该函数与ChargedItemgetChargedItemsQuery无关。 I realize I can just pass a function in for getChargeditemsQuery so that takes care of the that problem, but I am having issues with json.Unmarshal , for instance, when I try to use an interface, the json fields do not map correctly.我意识到我可以只为getChargeditemsQuery传递一个函数来getChargeditemsQuery这个问题,但是我遇到了json.Unmarshal问题,例如,当我尝试使用一个接口时,json 字段没有正确映射。 Is there a way to achieve what I'm trying to do without affecting the data models?有没有办法在不影响数据模型的情况下实现我想要做的事情?

I'm not sure what you're trying to do, but it's probably not a good idea.我不确定您要做什么,但这可能不是一个好主意。 At any rate, this should do what you are wanting:无论如何,这应该做你想要的:

package main

import (
   "encoding/json"
   "fmt"
)

func main() {
   // do what youre trying to do
   var (
      a = []byte("[10, 11]")
      b []interface{}
   )
   json.Unmarshal(a, &b)
   // then fix it later
   c := make([]float64, len(b))
   for n := range c {
      c[n] = b[n].(float64)
   }
   fmt.Println(c)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM