duanlinpi0265 2018-08-20 21:11
浏览 239

将两个JSON对象中的值连接到Go中的map [string] bool中

I am trying to concatenate two values, door and access, from a JSON object into a map[string]bool, which is declared inside a struct. Right now, I am getting the error:

json: cannot unmarshal string into Go struct field Data.pasted of type map[string]bool

The struct is defined as follows:

type AccessControl struct{
    SessionId string `json:"sessionId"`
    DoorAccess map[string]bool 
} 

The JSON object I am getting from the server is:

{
    "sessionId": "232",
    "door": "Main Door",
    "access": true
}

And this is my function:

func handler(w http.ResponseWriter, r *http.Request){
    var data AccessControl
    err := json.NewDecoder(r.Body).Decode(&data)
}
  • 写回答

2条回答 默认 最新

  • doremifasodo0008008 2018-08-20 21:15
    关注

    your json and your struct are not representing the same object your struct should be as follows:

        type AccessControl struct {
        SessionID string `json:"sessionId"`
        Door      string `json:"door"`
        Access    bool   `json:"access"`
        }
    

    and for the "full example" that you asked for:

    type ServerAccessControl struct {
        SessionID string `json:"sessionId"`
        Door      string `json:"door"`
        Access    bool   `json:"access"`
    }
    
    type AccessControl struct {
        SessionId  string `json:"sessionId"`
        DoorAccess map[string]bool
    }
    
    func main() {
        jsn := `{ "sessionId": "232", "door": "Main Door", "access": true }`
        var data ServerAccessControl
        json.Unmarshal([]byte(jsn), &data)
        accessControl := ServerAccessControlToAccessControl(&data)
        fmt.Println(accessControl)
    
    }
    
    //ServerAccessControlToAccessControl convert a access control obj from the server into a map based struct.
    func ServerAccessControlToAccessControl(fromServer *ServerAccessControl) AccessControl {
        var accessControl AccessControl
        accessControl.SessionId = fromServer.SessionID
        accessControl.DoorAccess = make(map[string]bool)
        accessControl.DoorAccess[fromServer.Door] = fromServer.Access
        return accessControl
    }
    

    I created the ServerAccessControl struct which represent the json that you are getting from the server and the Access Control class as you wanted it.

    It is important that you will notice that you are not getting a collection from the server, and if you plan to add more doors into your map, you will need to implement the logic your self.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题