Don’t even know what happens if you don’t tag a JSON package variable? Young man’s tail juice

Time:2021-7-13

Don't even know what happens if you don't tag a JSON package variable? Young man's tail juice

problem

jsonWhen used in the package, the variables in the structure are not addedtagCan it turn into normaljsonThe fields in?

How to answer

  • If variableInitial lowercase, thenprivate。 in any caseCan't turn, because you can’t get itReflection information
  • If variabletitle case, thenpublic

    • No tagCan be converted tojsonFields in the,jsonThe inner field name is the same as the inner fieldThe original name is the same
    • Added tag, fromstructturnjsonWhen I was young,jsonThe name of the field istagThe original field name is useless.

give an example

Through an example to deepen understanding.

package main
import (
    "encoding/json"
    "fmt"
)
type J struct {
    A string // lowercase without tag
    B string ` JSON: "B" '// lowercase + tag
    C string // uppercase without tag
    D string ` JSON: "DD" '// uppercase + tag
}
func main() {
    j := J {
      a: "1",
      b: "2",
      C: "3",
      D: "4",
    }
    FMT. Printf ("converted to the content of the pre-j structure of JSON =% + V / N", J)
    jsonInfo, _ := json.Marshal(j)
    FMT. Printf ("content converted to JSON =% + V / N", string (jsoninfo))
}

output

The content of the pre-j structure of JSON = {A: 1 B: 2 C: 3 D: 4}
Content converted to JSON = {"C": "3", "DD": "4"}

explain

  • There are four fields defined in the structure, corresponding toLowercase no tagLowercase + tagCapital without tagCapital + tag
  • TojsonLast initialLowercaseTag or notNot at allTojsonThe content of theCapitalizedAddedtagsureTake another nameWithout addingtagbejsonThe fields in are the same as the structure fieldsThe original name is the same

The article recommends:

If you want to learn one knowledge point every day?

Don't even know what happens if you don't tag a JSON package variable? Young man's tail juice