Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/coc1961/struconv
https://github.com/coc1961/struconv
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/coc1961/struconv
- Owner: coc1961
- License: mit
- Created: 2021-01-25T23:09:54.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2021-01-28T00:05:12.000Z (almost 4 years ago)
- Last Synced: 2024-03-22T04:43:23.748Z (9 months ago)
- Language: Go
- Size: 16.6 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# struconv
### Example
```go
package main
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings""github.com/coc1961/struconv"
)func main() {
// Create Scanner, that supports basic data conversion
c := struconv.New()// Add custom Converter for unknown Person Struct
c.AddScanner(struconv.Type(Person{}), PersonConverter{})var u User
// Map of data, Key = Struct Fields Name, Field data type or string
data := map[string]interface{}{
"UserID": "fgomez",
"Password": "x3f5h7j89x997",
"Person": "Fernado Gomez,35",
}// Fill struct User
err := c.Scan(&u, data)b, _ := json.MarshalIndent(u, "", " ")
fmt.Println(err)
fmt.Println(string(b))
//
// {
// "UserID": "fgomez",
// "Password": "x3f5h7j89x997",
// "Person": {
// "Name": "Fernado Gomez",
// "Age": 35
// }
// }}
type User struct {
UserID string
Password string
Person Person
}type Person struct {
Name string
Age int
}// Custom Converter
type PersonConverter struct{}// Convert Person to String
func (c PersonConverter) String(a interface{}) (string, error) {
p := a.(Person)
return fmt.Sprintf("%v,%v", p.Name, p.Age), nil
}// Convert and Set Value to User Field
func (c PersonConverter) Set(value *reflect.Value, s string) error {// Convert string to Person
fields := strings.Split(s, ",")age, _ := strconv.Atoi(fields[1])
person := Person{
Name: fields[0],
Age: age,
}// Set Person to User Field
value.Set(struconv.Value(person))
return nil
}```