Skip to content

Latest commit

 

History

History
58 lines (48 loc) · 1.39 KB

README.md

File metadata and controls

58 lines (48 loc) · 1.39 KB

Build Status Coverage Status

JSON validator and mapper

Validate JSON, and deserialize it into a structure without modifying or tagging the structure.

Example

package main

import "github.com/russellhaering/jsonmap"

type Dog struct {
	Name string
	Age  int
}

var DogTypeMap = jsonmap.StructMap{
	Dog{},
	[]jsonmap.MappedField{
		{
			StructFieldName: "Name",
			JSONFieldName:   "name",
			Validator:       jsonmap.String(1, 128),
		},
		{
			StructFieldName: "Age",
			JSONFieldName:   "age",
			Validator:       jsonmap.Integer(0, 1024),
		},
	},
}

var DemoTypeMapper = jsonmap.NewTypeMapper(
	DogTypeMap,
)

func main() {
	d := &Dog{}
	err := DemoTypeMapper.Unmarshal([]byte(`{"name": "Spot", "age": 4}`), d)
	if err != nil {
		panic(err)
	}
	println(d.Name)
	println(d.Age)
}

Why?

Use of struct tags to describe how to map JSON encourages bad design patterns. Developers end up putting JSON struct tags in places they have no business (like database objects, which should have no idea how some other layer might choose to serialize them) or writing tons of boiler plate to map API level structures to database objects. Using jsonmap is a way to avoid that boilerplate.