以下是Go中的示例代码。我想解析B的值并检查键' status'
的值package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName, status, sessionID, timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
if validateUser.status == "valid_user" {
fmt.Printf("Valid User")
}
}
答案 0 :(得分:3)
status
(ValidateUser.Status
)。只需稍微修改一下代码:
package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName string
// export Status, and map to json field `status`
Status string `json: "status"`
sessionID string
timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
// reference ValidateUser.Status (capital s)
if validateUser.Status == "valid_user" {
fmt.Printf("Valid User")
}
}
答案 1 :(得分:0)
del l[2:5]
#[1, 2, 6, 7]
包方法只能处理公共字段。在此处,json
是私有字段,无法通过status
或json.Marshal
访问。
如果您希望将字段名称设为json.Unmarshal
,则可以在status
中指定。
参见示例:
json tag
输出:
package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName string `json:"UserName"`
Status string `json:"Status"`
sessionID, timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
if validateUser.Status == "valid_user" {
fmt.Printf("Valid User: %v \n", validateUser)
jsonMarshalled, _ := json.Marshal(validateUser) //checking marshal
fmt.Println(string(jsonMarshalled))
}
}