github.com/rogpeppe/juju@v0.0.0-20140613142852-6337964b789e/environs/simplestreams/json.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package simplestreams
     5  
     6  import (
     7  	"encoding/json"
     8  	"reflect"
     9  )
    10  
    11  // itemCollection is a clone of ItemCollection, but
    12  // does not implement json.Unmarshaler.
    13  type itemCollection struct {
    14  	Items      map[string]*json.RawMessage `json:"items"`
    15  	Arch       string                      `json:"arch,omitempty"`
    16  	Version    string                      `json:"version,omitempty"`
    17  	Series     string                      `json:"release,omitempty"`
    18  	RegionName string                      `json:"region,omitempty"`
    19  	Endpoint   string                      `json:"endpoint,omitempty"`
    20  }
    21  
    22  // ItemsCollection.UnmarshalJSON unmarshals the ItemCollection,
    23  // storing the raw bytes for each item. These can later be
    24  // unmarshalled again into product-specific types.
    25  func (c *ItemCollection) UnmarshalJSON(b []byte) error {
    26  	var raw itemCollection
    27  	if err := json.Unmarshal(b, &raw); err != nil {
    28  		return err
    29  	}
    30  	c.rawItems = raw.Items
    31  	c.Items = make(map[string]interface{}, len(raw.Items))
    32  	c.Arch = raw.Arch
    33  	c.Version = raw.Version
    34  	c.Series = raw.Series
    35  	c.RegionName = raw.RegionName
    36  	c.Endpoint = raw.Endpoint
    37  	for key, rawv := range raw.Items {
    38  		var v interface{}
    39  		if err := json.Unmarshal([]byte(*rawv), &v); err != nil {
    40  			return err
    41  		}
    42  		c.Items[key] = v
    43  	}
    44  	return nil
    45  }
    46  
    47  func (c *ItemCollection) construct(itemType reflect.Type) error {
    48  	for key, rawv := range c.rawItems {
    49  		itemValuePtr := reflect.New(itemType)
    50  		err := json.Unmarshal([]byte(*rawv), itemValuePtr.Interface())
    51  		if err != nil {
    52  			return err
    53  		}
    54  		c.Items[key] = itemValuePtr.Interface()
    55  	}
    56  	return nil
    57  }