github.com/mantzas/incata@v0.3.0/marshal/json_marshaller.go (about)

     1  package marshal
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  )
     7  
     8  // JSONMarshaller JSON Serializer
     9  type JSONMarshaller struct {
    10  }
    11  
    12  // NewJSONMarshaller creates a new JSON serializer
    13  func NewJSONMarshaller() *JSONMarshaller {
    14  
    15  	return new(JSONMarshaller)
    16  }
    17  
    18  // Serialize JSON Implementation of serialization
    19  func (s *JSONMarshaller) Serialize(value interface{}) (interface{}, error) {
    20  
    21  	jsonArray, err := json.Marshal(value)
    22  
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  
    27  	return string(jsonArray), nil
    28  }
    29  
    30  // Deserialize JSON implementation of deserialization
    31  func (s *JSONMarshaller) Deserialize(value interface{}, result interface{}) error {
    32  
    33  	data, found := value.(string)
    34  
    35  	if !found {
    36  		return errors.New("value is not a string")
    37  	}
    38  
    39  	if err := json.Unmarshal([]byte(data), result); err != nil {
    40  		return err
    41  	}
    42  
    43  	return nil
    44  }