func NewDecoder(r io.Reader) *Decoder
is a function defined in the encoding/json
package which reads a JSON input stream, stores it in the buffer of a Decoder
object, and returns the Decoder
object. The Decoder
object can then be used to perform methods such as Decode()
, More()
, InputOutputOffset()
, Buffered()
.
r
: JSON readable stream that implements a io.Reader
interface
*Decoder
: Object of the type Decoder
defined in the encoding/json
package
package mainimport ("encoding/json""fmt""strings")func main() {const jsonStream = `{"Name": "Hassan", "Major": "Physics", "RollNumber": 18100026}`type Student struct {Name, Major stringRollNumber int32}dec := json.NewDecoder(strings.NewReader(jsonStream))var stu Student_ = dec.Decode(&stu)fmt.Printf("Student Information\nName: %s\t Major: %s\t RollNumber: %d\n", stu.Name, stu.Major, stu.RollNumber)}
In the above example, we define a struct Student
with properties Name
, Major
, and RollNumber
. We define jsonStream
with a JSON object and pass it to the strings.NewReader()
method to make a readable JSON stream. We pass the JSON stream to the func NewDecoder(r io.Reader) *Decoder
which returns a Decoder
object which is assigned to dec
. We use the Decode()
method accessible to dec
which decodes the JSON object into the properties of Student
and store in the stu
object.
Free Resources