lundi 22 mars 2021

create a new struct variable with reflect and keeping the struct tags

I'm having problems when trying to clone a struct with reflect.New and later marshaling to json, the result is not showing the json field names.

Here is a simplified version


type Person struct {
    Id        int     `json:"personid"`
    LastName  string  `json:"lastname"`
    FirstName string  `json:"firstname,omitempty"`
    Title     string  `json:"title"`
}


stmt := "select firstname,lastname from t_person"

rows := GetResults(db, stmt, Person{})

j, _ := json.Marshal(&rows)
log.Printf("persons: %s", j)



func GetResults(db *sql.DB, stmt string, p interface{}) []interface{} {

    rows, err := db.Query(stmt)
    if err != nil {
        log.Fatal(err)
    }

    t := reflect.TypeOf(p)

    var rs []interface{}
    for rows.Next() {
        // create new var
        n := reflect.New(t).Elem()

        pointers := make([]interface{}, 2)
        pointers[0] = n.Field(1).Addr().Interface()
        pointers[1] = n.Field(2).Addr().Interface()

        err := rows.Scan(pointers...)
        if err != nil {
            log.Fatal(err)
        }
        rs = append(rs, pointers)
    }

    return rs
}

I expected something like this ..

[ {"lastname":"don","firstname":"joe"}, {"lastname":"mary","firstname":"joe"} ... ]

but got

 [["don","joe"],["mary","joe"],["peter","pan"],["super","man"]]

any help will be appreciated





Aucun commentaire:

Enregistrer un commentaire