Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support json marshaller #44

Closed
mh-cbon opened this issue Feb 23, 2017 · 0 comments
Closed

support json marshaller #44

mh-cbon opened this issue Feb 23, 2017 · 0 comments

Comments

@mh-cbon
Copy link
Contributor

mh-cbon commented Feb 23, 2017

hi,

currently semver.Version does not support json (un)marshal interfaces.

When json encoded, it results in an empty string.
I suspect it happens because the struct won 't export any public fields.

See the demo code to work around this, alternatively,

package main

import (
	"encoding/json"
	"fmt"

	"github.com/Masterminds/semver"
)

type Jversion struct {
	*semver.Version
}

func NewJversion(s string) (*Jversion, error) {
	v, err := semver.NewVersion(s)
	if err != nil {
		return nil, err
	}
	return &Jversion{Version: v}, nil
}

func (a *Jversion) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	v, err := semver.NewVersion(s)
	if err != nil {
		return err
	}
	a.Version = v
	return nil
}

func (a *Jversion) MarshalJSON() ([]byte, error) {
	return json.Marshal(a.String())
}

func main() {
	s, err := NewJversion("0.0.1")
	kk(err)
	b, err2 := json.Marshal(s)
	kk(err2)
	fmt.Println(string(b))
}

func kk(err error) {
	if err != nil {
		panic(err)
	}
}
mattfarina added a commit that referenced this issue May 2, 2017
Add json (un)marshaling support (fixes #44)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant