Skip to content

Gin JSON Binding: Struct vs Map

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Gin JSON Binding: Struct vs Map. We cover key concepts, practical examples, and best practices.

JSON binding in Gin -- Bind request bodies correctly using ShouldBindJSON or ShouldBindWith to handle different content types.

The Problem

c.BindJSON() and c.ShouldBindJSON() require Content-Type application/json. If the client sends a different Content-Type, binding fails silently. Always check the binding error.

Wrong

func createUser(c *gin.Context) {
    var input struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }
    c.ShouldBindJSON(&input)
    c.JSON(200, input)
}

Output:

$ curl -X POST http://localhost:8080/users   -H "Content-Type: text/plain"   -d '{"name":"John"}'
{"name":"John","age":0}
func createUser(c *gin.Context) {
    var input struct {
        Name string `json:"name" binding:"required"`
        Age  int    `json:"age"`
    }
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    c.JSON(200, input)
}

Output:

$ curl -X POST http://localhost:8080/users   -d 'invalid json'
{"error":"invalid character 'i' looking for beginning of value"}

Prevention

  • Always check error from ShouldBindJSON
  • Use c.ShouldBindWith(&obj, binding.Query) for GET parameters
  • Use c.ShouldBindUri(&obj) for URI parameters
  • Set explicit Content-Type validation before binding
  • Use struct field tags for validation: binding:"required"

Common Mistakes with gin bound json

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is the difference between BindJSON and ShouldBindJSON?**

BindJSON calls c.AbortWithError. ShouldBindJSON returns the error. Prefer ShouldBindJSON.

Does Gin support XML binding?

Yes. Use c.ShouldBindXML(&obj) or c.ShouldBindWith(&obj, binding.XML).

How do I bind query parameters?

Use c.ShouldBindQuery(&obj). Struct fields use form:"field_name" tags.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro