Golang JSON processing struct not exporting Members

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


When we use Golang json to marshal a struct, the non-exported members of the struct will not be able to be accessed by JSON, that is, the result of JSON encoding will not appear (that is, lowercase members cannot export).

This is due to a technical problem: the name of the member in the Golang struct is not accessible if it starts with a lowercase letter, that is, JSON cannot access the member that begins with the lowercase letter in our struct


This can be solved in two ways.

1. The members of the struct start with uppercase, then add tag

2. Implement JSON. Marshaler interface


The first method is more common.

The second method is as follows

Http://play.golang.org/p/AiTwUOWkiT

Package Mainimport "FMT" import "Encoding/json" Func Main () {var s ss.a = 5s.b[0] = 3.123s.b[1] = 111.11s.b[2] = 1234.123s.c = "Hello" s.d[0] = 0x55j, _: = json. Marshal (s) fmt. Println (String (j))}type S struct {a intb [4]float32c stringd [12]byte}func (This S) Marshaljson () ([]byte, error) {return Json. Marshal (map[string]interface{}{"a": This.a, "B": this.b, "C": THIS.C, "D": THIS.D,})}

Output:

{"A": 5, "B": [3.123,111.11,1234.123,0], "C": "Hello", "D": [85,0,0,0,0,0,0,0,0,0,0,0]}


That is, the struct implements the Marshaljson () ([]byte, error) function, and in this function you export the members you want to export.

This makes it possible to use JSON as normal. A function like Marshal.


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.