I'm using the reflect package to create a re-usable JSON parser that maps JSON data to a particular struct at run-time.
I want it to detect when a particular required field is missing.
I create an variable "parsedInput" using:
parsedInput := reflect.New(reflect.TypeOf(exampleInputObject).Elem())
I've then used the JSON libraries to parse the data into that variable. I now want to traverse through the values to spot anything missing:
for i := 0; i < parsedInput.Elem().NumField(); i++ {
logger.Info("Field name was: " + field.Name)
fieldType := fmt.Sprintf("'%v'", field.Type.Kind().String())
logger.Info("Field type was: " + fieldType)
interfaceValue := fmt.Sprintf("'%v'", parsedInput.Elem().Field(i).Interface())
logger.Info("Interface value was: " + interfaceValue)
//Look to see if the field is a null pointer. If so, this could be an issue
if (field.Type.Kind().String() == "ptr") && (parsedInput.Elem().Field(i).Interface() == nil) {
//Do null pointer stuff here
}
}
For the field that's missing, I see the log output
Field name was: MissingFieldName
Field type was 'ptr'
Interface value was '<nil>'
My code is never dropping into the null pointer logic however - what am I doing wrong?
As per comment above - I managed to solve this using built-in functions in the Reflect package - specifically by testing for:
Reflect.ValueOf(parsedInput.Elem().Field(i).Interface()).IsNil()
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.