Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
v2_example_marshaling_test.go77 linesDownload Raw Back to json
1// Copyright 2016 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5//go:build goexperiment.jsonv26 7package json_test8 9import (10	"fmt"11	"log"12	"strings"13 14	"encoding/json"15)16 17type Animal int18 19const (20	Unknown Animal = iota21	Gopher22	Zebra23)24 25func (a *Animal) UnmarshalJSON(b []byte) error {26	var s string27	if err := json.Unmarshal(b, &s); err != nil {28		return err29	}30	switch strings.ToLower(s) {31	default:32		*a = Unknown33	case "gopher":34		*a = Gopher35	case "zebra":36		*a = Zebra37	}38 39	return nil40}41 42func (a Animal) MarshalJSON() ([]byte, error) {43	var s string44	switch a {45	default:46		s = "unknown"47	case Gopher:48		s = "gopher"49	case Zebra:50		s = "zebra"51	}52 53	return json.Marshal(s)54}55 56func Example_customMarshalJSON() {57	blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`58	var zoo []Animal59	if err := json.Unmarshal([]byte(blob), &zoo); err != nil {60		log.Fatal(err)61	}62 63	census := make(map[Animal]int)64	for _, animal := range zoo {65		census[animal] += 166	}67 68	fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",69		census[Gopher], census[Zebra], census[Unknown])70 71	// Output:72	// Zoo Census:73	// * Gophers: 374	// * Zebras:  275	// * Unknown: 376}77 
codekingpro/portable-devtools · Team Ai