Go Struct Tags: Marshaling and Unmarshaling JSON Data
Struct tags in Go provide a powerful mechanism for associating metadata with struct fields. This metadata can be used by libraries to control behavior, such as how data is marshaled and unmarshaled into different formats. In this challenge, you'll leverage struct tags to customize JSON encoding and decoding for a User struct.
Problem Description
Your task is to create a User struct with fields for ID, Username, Email, and IsActive. You need to use Go struct tags to specify how these fields should be represented when marshaling to and unmarshaling from JSON.
Specifically:
- The
IDfield should be represented as"user_id"in JSON. - The
Usernamefield should be represented as"name"in JSON. - The
Emailfield should be represented as"email_address"in JSON. - The
IsActivefield should be represented as"active"in JSON. - You should also handle the case where a JSON field might be missing or empty.
You will need to use the encoding/json package to perform the marshaling and unmarshaling operations.
Examples
Example 1:
Input Struct:
User{ID: 1, Username: "alice", Email: "alice@example.com", IsActive: true}
JSON Output:
{"user_id":1,"name":"alice","email_address":"alice@example.com","active":true}
Explanation: The struct fields are marshaled into JSON according to their respective struct tags.
Example 2:
Input JSON:
{"user_id": 2, "name": "bob", "email_address": "bob@example.com"}
Output Struct:
User{ID: 2, Username: "bob", Email: "bob@example.com", IsActive: false}
Explanation: The JSON fields are unmarshaled into the struct. Since "active" is missing in the JSON, the `IsActive` field defaults to its zero value (false for boolean).
Example 3:
Input JSON:
{"user_id": 3, "active": true}
Output Struct:
User{ID: 3, Username: "", Email: "", IsActive: true}
Explanation: Fields like "name" and "email_address" are missing in the JSON, so their corresponding struct fields will receive their zero values ("" for strings). The "active" field is present and correctly unmarshaled.
Constraints
- The
IDfield will always be an integer. - The
Username,Emailfields will always be strings. - The
IsActivefield will always be a boolean. - The input JSON will conform to valid JSON syntax.
- There are no strict performance constraints for this challenge.
Notes
- The
encoding/jsonpackage in Go is your primary tool. - Pay close attention to the syntax for defining struct tags in Go.
- Consider how the
encoding/jsonpackage handles missing fields during unmarshaling. - You will be implementing marshaling (struct to JSON) and unmarshaling (JSON to struct).