Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value golang struct using `encoding/json` ?

Tags:

go

How to set default value for Encoding as "base64"?

type FileData struct {
    UID string `json:"uid"`                 
    Size int `json:"size"`
    Content string `json:content`
    Encoding string `json:encoding` 
    User string `json:"user"`
}

I tried

Encoding string `json:encoding`= "base64" // Not working
like image 447
Jagdish Idhate Avatar asked Aug 26 '16 07:08

Jagdish Idhate


2 Answers

You can set default value when you init your 'FileData'
See my example: https://play.golang.org/p/QXwDG7_mul
Page int has default value 33

package main

import (
    "encoding/json"
    "fmt"
)

type Response2 struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {
    str := `{"fruits": ["apple", "peach"]}`
    res := Response2{Page: 33 /*Default value*/}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res)
}
like image 90
Son Bui Avatar answered Nov 02 '22 08:11

Son Bui


Since your FileData isn't too complex, you can easily make use of json.Unmarshaler interface. Declare Encoding as a separate type and set the default value in the unmarshal method:

type FileData struct {
    UID string `json:"uid"`                 
    Size int `json:"size"`
    Content string `json:content`
    Encoding Encoding `json:encoding` // declared as a custom type
    User string `json:"user"`
}

type Encoding string

// implement the Unmarshaler interface on Encoding
func (e *Encoding) UnmarshalJSON(b []byte) error {
    var s string
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }
    if s == "" {
        *e = Encoding("base64")
    } else {
        *e = Encoding(s)
    }
    return nil
}

Now when you encode a json with empty Encoding value, it'll be set to base64:

var data1 = []byte(`{"uid": "UID", "size": 10, "content": "CONTENT", "encoding": "ASCII", "user": "qwe"}`)
var data2 = []byte(`{"uid": "UID", "size": 10, "content": "CONTENT", "encoding": "", "user": "qwe"}`)

func main() {
    fmt.Println("Hello, playground")
    f := FileData{}
    if e := json.Unmarshal(data1, &f); e != nil {
        fmt.Println("Error:", e)
    }
    fmt.Println(f, f.Encoding)
    if e := json.Unmarshal(data2, &f); e != nil {
        fmt.Println("Error:", e)
    }
    fmt.Println(f, f.Encoding)
}

Output:

{UID 10 CONTENT ASCII qwe} ASCII
{UID 10 CONTENT base64 qwe} base64

Working code: https://play.golang.org/p/y5_wBgHGJk

like image 12
abhink Avatar answered Nov 02 '22 06:11

abhink