Golang Some example code for JSON processing

Source: Internet
Author: User
Tags gopher pear
This is a creation in Article, where the information may have evolved or changed.

JSON processing example code, parsing results look at the following comments.

Package Main

Import "Encoding/json"
Import "FMT"
Import "OS"

Type Response1 struct {
Page int
Fruits []string
}

Type Response2 struct {
Page int ' JSON: ' Page '
Fruits []string ' JSON: "Fruits" '
}

Type Commonarg struct {
SessionId Int64 ' JSON: ", string" '
Op string ' JSON: ' Op,omitempty '
AppId string ' JSON: ' Appid,omitempty '
Online BOOL
}

Func Main () {
Bolb, _: = json. Marshal (True)
Fmt. Println (String (BOLB))//True

IntB, _: = json. Marshal (1)
Fmt. Println (String (IntB))//1

FLTB, _: = json. Marshal (2.34)
Fmt. Println (String (FLTB))//2.34

StrB, _: = json. Marshal ("Gopher")
Fmt. Println (String (StrB))//"Gopher"

SLCD: = []string{"Apple", "peach", "pear"}
SLCB, _: = json. Marshal (SLCD)
Fmt. Println (String (SLCB))//["Apple", "peach", "pear"]

MAPD: = map[string]int{"Apple": 5, "lettuce": 7}
MAPB, _: = json. Marshal (MAPD)
Fmt. Println (String (MAPB))//{"Apple": 5, "lettuce": 7}

RES1D: = &response1{
Page:1,
Fruits: []string{"Apple", "peach", "Pear"}}
Res1b, _: = json. Marshal (RES1D)
Fmt. Println (String (RES1B))//{"page": 1, "Fruits": ["apple", "peach", "Pear"]}

Res2d: = &response2{
Page:1,
Fruits: []string{"Apple", "peach", "Pear"}}
Res2b, _: = json. Marshal (res2d)
Fmt. Println (String (RES2B))//{"page": 1, "Fruits": ["apple", "peach", "Pear"]}

AAA: = &commonarg{
sessionid:12345,
Op: "werdfsdde22233",
AppId: "654343DFDDD33424DD",
Online:false,
}
Aaa1, _: = json. Marshal (AAA)
Fmt. Println (String (AAA1))//{"SessionId": "12345", "Op": "werdfsdde22233", "appId": "654343DFDDD33424DD", "Online": false}

BYT: = []byte (' {"num": 6.0, "STRs": ["a", "B"]} ')

var dat map[string]interface{}

If err: = json. Unmarshal (byt, &dat); Err! = Nil {
Panic (ERR)
}
Fmt. PRINTLN (DAT)//map[strs:[a B] num:6]

Num: = dat["num"]. (float64)
Fmt. PRINTLN (num)//6

STRs: = dat["STRs"]. ([]interface{})
STR1: = Strs[0]. (string)
Fmt. PRINTLN (STR1)//A

str: = ' {"page": 1, "fruits": ["apple", "Peach"]} '
Res: = &response2{}
Json. Unmarshal ([]byte (str), &res)
Fmt. PRINTLN (RES)//&{1 [Apple Peach]}
Fmt. Println (Res. FRUITS[0])//Apple

ENC: = json. Newencoder (OS. Stdout)
D: = map[string]int{"Apple": 5, "lettuce": 7}
Enc. Encode (d)//{"Apple": 5, "lettuce": 7}
}

Note that the struct field ' s tag specification for JSON here is defined as follows:

In the go language, Structtag is a token string that can be followed by a field definition in a struct.

Structtag is a series of keys: A combination of "value" forms, where key is a non-nullable string, and the Key-value combination can have multiple, space-delimited.

What's the use of Structtag?! Structtag mainly solves the problem that the key value key is not defined in the conversion between different types of data sets (struct,json,table, etc.). Structtag can be understood as a map of a different data type key value key, in Structtag can define different data set key values and the mapping of the key value in the struct, which facilitates the process of conversion of the struct data to other types of data.

Add "Omitempty" to the Structtag, and the data that identifies the field can be ignored.

-When assigned to a field, the field is ignored regardless of whether the value is serialized as JSON

Refer to the following code, code from: http://studygolang.com/articles/1698:

Package Main

Import (
    encoding/json
    fmt
)

The first parameter in tag is used to specify an alias
For example, name specifies the alias username ' JSON: ' username '
If you do not want to specify an alias but want to specify additional parameters separated by commas
Omitempty when assigned to a field if the property is assigned a value at the time of assignment or the property is assigned a value of zero value
The field is ignored when the person is serialized as JSON
-When specifying to a field
This field is ignored regardless of whether a value serializes a person into JSON
When a string is specified to a field
For example, the count in person is an int type if there is no specified in the serialization
After the JSON is also int like this "Count": 0
However, if a string is specified after serialization is also a string type
So that's what it looks like. "Count": "0"
Type person struct {
Name string ' JSON: ' username '
Age int
Gender BOOL ' JSON: ", Omitempty" '
Profile string
Omitcontent string ' JSON: '-'
Count int ' json: ", string" '
}

Func Main () {

    var p *person = &person{
        name:         "Brainwu",
        age:         ,
        gender:       True,
        profile:     "I am ghj1976",
        omitcontent: "Omitconent",
   }
     If BS, err: = json. Marshal (&P); Err! = Nil {
        panic (err)
   } else {
  & nbsp;    //result-to {"username": "Brainwu", "age": +, "Gender": True, "Profile": "I am ghj1976" , "Count": "0"}
        fmt. Println (String (BS))
   }

    var P2 *person = &person{
        name:  & nbsp;     "Brainwu",
        age:         ,
        profile:      "I am ghj1976",
        omitcontent: "Omitconent",
    }
    if BS, err: = json. Marshal (&P2); Err! = Nil {
        panic (err)
   } else {
  & nbsp;    //result-to {"username": "Brainwu", "age": +, "Profile": "I am ghj1976", "Count": "0"}
        FMT. Println (String (BS))
   }

   //Slice serialized as JSON
    var aStr []string = []string{"Go", "Java", "Python", "Andro ID "}
    if BS, err: = json. Marshal (ASTR); Err! = Nil {
        panic (err)
   } else {
  & nbsp;    //result---["Go", "Java", "Python", "Android"]
         FMT. Println (String (BS))
   }

Map serialized as JSON
var m map[string]string = Make (map[string]string)
m["Go" = "the Most"
m["Java"] = "No.2"
m["C"] = "No.3"
If BS, err: = json. Marshal (m); Err! = Nil {
Panic (ERR)
} else {
Result----{"C": "No.3", "Go": "The Most", "Java": "No.2"}
Fmt. Println (String (BS))
}
}

Reference:

Structtag types in the Go language
http://www.wangwei.info/2013/11/golang-struct-tag/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.