简体   繁体   中英

Golang Dynamically Unmarshalling JSON

Is it possible in Go, given the below function, to unmarshall jsonString without knowing the type of c at runtime?

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 . 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. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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