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

Add json marshalling compatibility #796

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions retrievalmarket/bindnodeoptions.go
Expand Up @@ -6,6 +6,7 @@ import (
"io"

"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/codec/dagjson"
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/node/basicnode"
"github.com/ipld/go-ipld-prime/node/bindnode"
Expand Down Expand Up @@ -81,6 +82,34 @@ func (sn *CborGenCompatibleNode) MarshalCBOR(w io.Writer) error {
return dagcbor.Encode(node, w)
}

// MarshalJSON is for encoding/json compatibility
func (sn *CborGenCompatibleNode) MarshalJSON() ([]byte, error) {
node := datamodel.Null
if sn != nil && sn.Node != nil {
node = sn.Node
if tn, ok := node.(schema.TypedNode); ok {
node = tn.Representation()
}
}
buf := new(bytes.Buffer)
err := dagjson.Encode(node, buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
Comment on lines +94 to +99
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
buf := new(bytes.Buffer)
err := dagjson.Encode(node, buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
return ipld.Encode(node, dagjson.Encode)

}

// UnmarshalJSON is for encoding/json compatibility
func (sn *CborGenCompatibleNode) UnmarshalJSON(data []byte) error {
// convert it to a Node
na := basicnode.Prototype.Any.NewBuilder()
if err := dagcbor.Decode(na, bytes.NewReader(data)); err != nil {
return err
}
sn.Node = na.Build()
Comment on lines +105 to +109
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
na := basicnode.Prototype.Any.NewBuilder()
if err := dagcbor.Decode(na, bytes.NewReader(data)); err != nil {
return err
}
sn.Node = na.Build()
node, err := ipld.Decode(data, dagjson.Decode)
if err != nil {
return err
}
sn.Node = node

return nil
}

func cborGenCompatibleNodeFromAny(node datamodel.Node) (interface{}, error) {
return &CborGenCompatibleNode{Node: node}, nil
}
Expand Down