jsonutil

package
v0.0.0-...-c6ea6ab Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2021 License: LGPL-3.0 Imports: 5 Imported by: 0

README

jsonutil

GoDoc

Features

  • support omitdefault json flag and default tag
  • support omitempty on struct/slice
  • support wrapper json flag
  • support IsEmpty interface

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrorUnsupportedMarshalType2 = errutil.NewFactory("unsupported marshal type: %s (%s)")
)

errors

Functions

func MarshalJSON

func MarshalJSON(v interface{}) ([]byte, error)

MarshalJSON marshal JSON with extended flags

Example
package main

import (
	"fmt"

	"github.com/tsaikd/KDGoLib/jsonutil"
)

func main() {
	type myStruct struct {
		String string
	}
	data, _ := jsonutil.MarshalJSON(myStruct{
		String: "text",
	})
	fmt.Printf("%s\n", data)
}
Output:

{"String":"text"}
Example (Omitdefault_string)
package main

import (
	"fmt"

	"github.com/tsaikd/KDGoLib/jsonutil"
)

func main() {
	type myStruct struct {
		String string `json:",omitdefault" default:"text"`
	}
	data, _ := jsonutil.MarshalJSON(myStruct{
		String: "text",
	})
	fmt.Printf("%s\n", data)
}
Output:

{}
Example (Omitempty_struct)
package main

import (
	"fmt"

	"github.com/tsaikd/KDGoLib/jsonutil"
)

func main() {
	type subStruct struct {
		String string `json:",omitdefault" default:"text"`
	}
	type myStruct struct {
		SubStruct subStruct `json:",omitempty"`
	}
	data, _ := jsonutil.MarshalJSON(myStruct{
		subStruct{
			String: "text",
		},
	})
	fmt.Printf("%s\n", data)
}
Output:

{}

Types

type IsEmpty

type IsEmpty interface {
	IsEmpty() bool
}

IsEmpty implement IsEmpty() instance

Example

Custom struct with IsEmpty() interface will change the marshal output

package main

import (
	"fmt"

	"github.com/tsaikd/KDGoLib/jsonutil"
)

type emptyStruct struct {
	String string
	empty  bool
}

func (t emptyStruct) IsEmpty() bool {
	return t.empty
}

// Custom struct with IsEmpty() interface will change the marshal output
func main() {
	data1, _ := jsonutil.MarshalJSON(emptyStruct{
		String: "text",
		empty:  false,
	})
	data2, _ := jsonutil.MarshalJSON(emptyStruct{
		String: "text",
		empty:  true,
	})
	fmt.Printf("%s\n", data1)
	fmt.Printf("%s\n", data2)
}
Output:

{"String":"text"}
null

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL