github.com/ipld/go-ipld-prime@v0.21.0/codecHelpers_test.go (about)

     1  package ipld_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/ipld/go-ipld-prime"
     7  	"github.com/ipld/go-ipld-prime/codec/json"
     8  	"github.com/ipld/go-ipld-prime/must"
     9  	"github.com/ipld/go-ipld-prime/schema"
    10  )
    11  
    12  func Example_marshal() {
    13  	type Foobar struct {
    14  		Foo string
    15  		Bar string
    16  	}
    17  	encoded, err := ipld.Marshal(json.Encode, &Foobar{"wow", "whee"}, nil)
    18  	fmt.Printf("error: %v\n", err)
    19  	fmt.Printf("data: %s\n", string(encoded))
    20  
    21  	// Output:
    22  	// error: <nil>
    23  	// data: {
    24  	// 	"Foo": "wow",
    25  	// 	"Bar": "whee"
    26  	// }
    27  }
    28  
    29  // TODO: Example_Unmarshal, which uses nil and infers a typesystem.  However, to match Example_Unmarshal_withSchema, that appears to need more features in bindnode.
    30  
    31  func Example_unmarshal_withSchema() {
    32  	typesys := schema.MustTypeSystem(
    33  		schema.SpawnStruct("Foobar",
    34  			[]schema.StructField{
    35  				schema.SpawnStructField("foo", "String", false, false),
    36  				schema.SpawnStructField("bar", "String", false, false),
    37  			},
    38  			schema.SpawnStructRepresentationMap(nil),
    39  		),
    40  		schema.SpawnString("String"),
    41  	)
    42  
    43  	type Foobar struct {
    44  		Foo string
    45  		Bar string
    46  	}
    47  	serial := []byte(`{"foo":"wow","bar":"whee"}`)
    48  	foobar := Foobar{}
    49  	n, err := ipld.Unmarshal(serial, json.Decode, &foobar, typesys.TypeByName("Foobar"))
    50  	fmt.Printf("error: %v\n", err)
    51  	fmt.Printf("go struct: %v\n", foobar)
    52  	fmt.Printf("node kind and length: %s, %d\n", n.Kind(), n.Length())
    53  	fmt.Printf("node lookup 'foo': %q\n", must.String(must.Node(n.LookupByString("foo"))))
    54  
    55  	// Output:
    56  	// error: <nil>
    57  	// go struct: {wow whee}
    58  	// node kind and length: map, 2
    59  	// node lookup 'foo': "wow"
    60  }