I was working through an example on marshalling and decided to get crafty with it. Was hoping I could have a generic interface reference passed in similar to the json.Unmarshall
function and handle my other test cases by input instead of repeating the same code (yes, I'm coming from Java). Instead, I get back a map instead of a struct. It also appears I do not have a way to imply downwards what this 'type' of struct is.
Questions:
- How would I be able to get the appropriate struct type back?
- Is it even reasonable to take this approach of a utility method like this?
Code:
//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
}
Have also tried marshalling to nptr := reflect.New(reflect.TypeOf(v))
, but this ended me with an address I could not resolve.
Output:
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>