Created
December 13, 2014 15:01
-
-
Save hiroosak/c70066ed92b0c847f499 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"github.com/xeipuuv/gojsonschema" | |
"fmt" | |
) | |
type User struct { | |
Name string | |
Age uint16 | |
Articles []Article | |
} | |
type Article struct { | |
Title string | |
Content string | |
} | |
func main() { | |
var jsonStr = `{ | |
"Name": "Ken", | |
"Age": 32, | |
"Articles": [ | |
{"Title": "Title A", "Content": "content A"}, | |
{"Title": "Title B", "Content": "content B"} | |
] | |
}` | |
schema := `{ | |
"type": "object", | |
"properties": { | |
"Name": { | |
"type": "string" | |
}, | |
"Age": { | |
"type": "integer" | |
}, | |
"Articles": { | |
"type": "array", | |
"items": { | |
"type": "object", | |
"properties": { | |
"Title": { | |
"type": "string" | |
}, | |
"Content": { | |
"type": "string" | |
} | |
}, | |
"additionalProperties": false, | |
"required": ["Title", "Content"] | |
} | |
} | |
}, | |
"additionalProperties": false, | |
"required": ["Name", "Age", "Articles"] | |
}` | |
var j map[string]interface{} | |
err := json.Unmarshal([]byte(schema), &j) | |
if err != nil { | |
panic(err) | |
} | |
schemaDocument, err := gojsonschema.NewJsonSchemaDocument(j) | |
if err != nil { | |
panic(err) | |
} | |
var jsonBody interface{} | |
err = json.Unmarshal([]byte(jsonStr), &jsonBody) | |
if err != nil { | |
panic(err) | |
} | |
result := schemaDocument.Validate(jsonBody) | |
if result.Valid() == false { | |
panic("err") | |
} | |
var u User | |
err = json.Unmarshal([]byte(jsonStr), &u) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(u) // {Ken 32 [{Title A content} {Title B content}]} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment