JSON

As the convention in JSON is for map keys to be in lowercase, we add hints to our struct of the `json:"subject"` form that tell the json package how to handle the field names within the struct. The updated definition should look like the following code:

type EmailMessage struct {
Subject string `json:"subject"`
Content string `json:"content"`
To Email `json:"to"`
From Email `json:"from"`
Date time.Time `json:"sent"`
}

To aid in testing, let's also add a String() function to the definition for easier debugging later:

func (e *EmailMessage) String() string {
format := "EmailMessage{ To:%s From:%s Subject:%s Date:%s }"
return fmt.Sprintf(format, e.To, e.From, e.Subject, e.Date.String())
}

Once this is in place, we can add some code that demonstrates the usage. Firstly, let's construct a new EmailMessage object and encode it to JSON. The encoding is very simple, and is illustrated as follows. We just create a new json.Encoder instance (that will output to the standard output), set the indent values (for improved readability), and ask it to encode our struct:

fmt.Println("To JSON:")
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
encoder.Encode(email)

Decoding a struct from JSON is also simple. We connect to a URL, open a stream using code from earlier in this chapter (the URL is omitted here for brevity), and defer the closing of the stream. Then, a new json.Decoder instance is created from this stream and we ask it to decode into the email struct. We'll then output the data (using the preceding helpful String() function) to see the result:

stream := readStream(urlOmitted)
defer stream.Close()

email := &EmailMessage{}
json.NewDecoder(stream).Decode(email)
fmt.Println("Downloaded:", email)

Running all of that'll result in some pretty easy-to-read output that shows we've successfully created, encoded, and then decoded JSON data for our struct:

JSON data from a struct and from a WebService
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.182.62