dsa1234569 2013-02-02 22:38
浏览 6
已采纳

为JSON编码器/解码器“发布”了不同的结构属性

I need to export some large structs via JSON, and take back JSON strings for updating only some of it's attributes.

Let's have following struct:

type House struct {
    Name   string  `json:"name"`
    Rooms  int     `json:"rooms_count"`
    Owner  *Owner  `json:"-"`
}

Encoding that with encoding/json will result in a JSON string like

{"name":"some name", "rooms_count":5}

I now get this JSON string:

{"name":"some other name", "rooms_count":7, Owner:{something...}}

The user wants to change every attribute. Owner is not allowed, because it's not exported. But I only want to only permit changes of rooms_count. Is there any way of saying that some attributes should be exported with the Encoder, but not be used by the Decoder? Having to write all these checks manualy would be very unpleasant.

  • 写回答

2条回答 默认 最新

  • donglu8344812 2013-02-03 13:27
    关注

    I created a patch for the encoding/json package and opened a ticket.

    It just adds 2 tag options for structs for ignoring struct fields in the Encoder and Decoder separately. Example where all two fields are encoded/exported, but only Name is getting decoded/updated:

    type House struct {
        Name    string    `json:"house_name"`
        PubDate time.Time `json:"pub_date,nodecode"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP