Go: JSON Encoding
Create a JSON-encoding system for objects.
Write a struct called Manager with fields FullName and Position (both string), then Age and YearsInCompany (both int32) – in that exact order. Also write a function that encodes objects of this struct to an encoded JSON object. It returns an io.Reader with this JSON object. Fields in the JSON object should be renamed as full_name, position, age and years_in_company. Empty fields should be omitted.
Example
A Manager is named Chris Smith, the CISO, who is 32 years old. Chris has worked with the company for 5 years. This data should be encoded to {“full_name”:”Chris Smith”,”age”:32,”position”:”CISO”,”years_in_company”:5}.
Function Description
Complete the function EncodeManager in the editor below.
EncodeManager has the following parameter:
manager: an object of type *Manager (the pointer to the Manager)
Returns
io.reader, error: two objects must be returned
Constraints
- 1 ≤ length of full_name, position ≤ 100
- 1 ≤ age, years_in_company ≤ 100
SOLUTIONS:
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
)
type Manager struct {
FullName string `json:"full_name,omitempty"`
Position string `json:"position,omitempty"`
Age int32 `json:"age,omitempty"`
YearsInCompany int32 `json:"years_in_company,omitempty"`
}
func EncodeManager(manager *Manager) (io.Reader, error) {
encodedJSON, err := json.Marshal(manager)
if err != nil {
return nil, err
}
return bytes.NewReader(encodedJSON), nil
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 16*1024*1024)
manager := &Manager{}
fullName := readLine(reader)
if fullName != "" {
manager.FullName = fullName
}
position := readLine(reader)
if position != "" {
manager.Position = position
}
ageTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
age := int32(ageTemp)
if age != 0 {
manager.Age = age
}
yearsInCompanyTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
yearsInCompany := int32(yearsInCompanyTemp)
if yearsInCompany != 0 {
manager.YearsInCompany = yearsInCompany
}
resultReader, err := EncodeManager(manager)
checkError(err)
result, err := ioutil.ReadAll(resultReader)
checkError(err)
fmt.Fprintf(writer, "%s\n", string(result))
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}