github.com/trim21/go-phpserialize@v0.0.22-0.20240301204449-2fca0319b3f0/example_test.go (about)

     1  package phpserialize_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/trim21/go-phpserialize"
     7  )
     8  
     9  func ExampleMarshal() {
    10  	type User struct {
    11  		ID   uint32 `php:"id,string"`
    12  		Name string `php:"name"`
    13  	}
    14  
    15  	type Inner struct {
    16  		V int    `php:"v"`
    17  		S string `php:"a long string name replace field name"`
    18  	}
    19  
    20  	type With struct {
    21  		Users   []User `php:"users,omitempty"`
    22  		Obj     Inner  `php:"obj"`
    23  		Ignored bool   `php:"-"`
    24  	}
    25  
    26  	var data = With{
    27  		Users: []User{
    28  			{ID: 1, Name: "sai"},
    29  			{ID: 2, Name: "trim21"},
    30  		},
    31  		Obj: Inner{V: 2, S: "vvv"},
    32  	}
    33  	var b, err = phpserialize.Marshal(data)
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  
    38  	fmt.Println(string(b))
    39  	// Output: a:2:{s:5:"users";a:2:{i:0;a:2:{s:2:"id";s:1:"1";s:4:"name";s:3:"sai";}i:1;a:2:{s:2:"id";s:1:"2";s:4:"name";s:6:"trim21";}}s:3:"obj";a:2:{s:1:"v";i:2;s:37:"a long string name replace field name";s:3:"vvv";}}
    40  }
    41  
    42  func ExampleUnmarshal() {
    43  	var v struct {
    44  		Value map[string]string `php:"value" json:"value"`
    45  	}
    46  	raw := `a:1:{s:5:"value";a:5:{s:3:"one";s:1:"1";s:3:"two";s:1:"2";s:5:"three";s:1:"3";s:4:"four";s:1:"4";s:4:"five";s:1:"5";}}`
    47  
    48  	err := phpserialize.Unmarshal([]byte(raw), &v)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  
    53  	fmt.Println(v.Value["five"])
    54  	// Output: 5
    55  }