dougai3418 2018-10-31 08:16
浏览 1204

在Golang中,执行Marshal和Unmarshal时JSON字段名称的大小写是否重要?

Are Marshal and Unmarshal functions strictly case sensitive?

The following structure defines a ticket:

    type TicketInfo struct {

         TicketKey                  string `json:"ticketKey"`       
         Ticketextnum               string `json:"ticketextnum"`        
         TicketDate                 string `json:"ticketDate"`      
         TicketDesc                 string `json:"ticketDesc"`
    }       

This stringified form of this json will be passed as a single parameter in the payload of an API call by the source systems. What will happen if the source system sends, for example, "TicketKey" instead of "ticketKey" for the first field. Will json.Marshal correctly received the ticketKey field?

  • 写回答

1条回答 默认 最新

  • ds1379551 2018-10-31 08:27
    关注

    This is easily answered by reading the docs, or with a simple test. But specifically, see these notes (emphasis added) for Marshal:

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

    The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

    and Unmarshal:

    To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

    So TL;DR; for marshaling, case is observed exactly, and for unmarshaling, exact case is preferred with a fallback to a case-insensitive match.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号