解析在 POST 请求中发送的 json 正文数组并打印
Parse json body array sent in POST request and print
我在读取 json 数组时遇到一个问题。需要以下查询的帮助。
请求Json:
{ "httpReq": {
"username": "1234567890",
"password": "1234567890",
"number": "123456"
}
}
回应Json:
{ "httpResp": {
"status": "Pass",
"message": "great"
}
}
下面是我的代码:如果我在其工作下方传递 json 对象,但我需要在 json 中发送“httpReq”。
package main
import (
"encoding/json"
"fmt"
)
type people struct {
Username string `json:"username"`
Password string `json:"password"`
Number string `json:"number"`
}
type peopleread struct {
Collection []people
}
func main() {
text := `{
"username": "1234567890",
"password": "1234567890",
"number": "123456"
}`
textBytes := []byte(text)
//people1 := people{}
var people2 people
err := json.Unmarshal(textBytes, &people2)
if err != nil {
fmt.Println(err)
return
}
Username := people2.Username
Password := people2.Password
Number := people2.Number
fmt.Println(Username)
fmt.Println(Password)
fmt.Println(Number)
}
要使用 httpReq
字段解组,您必须处理这个问题。
创建一个结构来包装您的请求正文,例如 json
type HttpReq struct{
HttpReq people `json:"httpReq"`
}
然后使用解组
var httpReq HttpReq
err := json.Unmarshal(textBytes, &httpReq)
Go playground 中的完整代码 here
我在读取 json 数组时遇到一个问题。需要以下查询的帮助。
请求Json:
{ "httpReq": {
"username": "1234567890",
"password": "1234567890",
"number": "123456"
}
}
回应Json:
{ "httpResp": {
"status": "Pass",
"message": "great"
}
}
下面是我的代码:如果我在其工作下方传递 json 对象,但我需要在 json 中发送“httpReq”。
package main
import (
"encoding/json"
"fmt"
)
type people struct {
Username string `json:"username"`
Password string `json:"password"`
Number string `json:"number"`
}
type peopleread struct {
Collection []people
}
func main() {
text := `{
"username": "1234567890",
"password": "1234567890",
"number": "123456"
}`
textBytes := []byte(text)
//people1 := people{}
var people2 people
err := json.Unmarshal(textBytes, &people2)
if err != nil {
fmt.Println(err)
return
}
Username := people2.Username
Password := people2.Password
Number := people2.Number
fmt.Println(Username)
fmt.Println(Password)
fmt.Println(Number)
}
要使用 httpReq
字段解组,您必须处理这个问题。
创建一个结构来包装您的请求正文,例如 json
type HttpReq struct{
HttpReq people `json:"httpReq"`
}
然后使用解组
var httpReq HttpReq
err := json.Unmarshal(textBytes, &httpReq)
Go playground 中的完整代码 here