区分大小写的JSON Unmarshal结构 [英] JSON Unmarshal struct case-sensitively
问题描述
有没有办法使json.Unmarshal 不接受不区分大小写的匹配?我收到带有标签的JSON,例如"e"和"E",并想解组带有标签"e"的对象,但忽略带有"E"的对象.现在,我发现的唯一解决方案是定义一个包含两个标签的结构,然后简单地忽略标签"E",但是我正在寻找一种更清洁的解决方案.
Is there any way to make json.Unmarshal not accept a case-insensitive match? I receive a JSON with tags such as "e" and "E" and would like to unmarshal the object with tag "e" but ignore the one with "E". Right now the only solution I found was to define a struct containing both tags and then to simply ignore tag "E", but I'm looking for a cleaner solution.
摘自官方文档:
要将JSON解组到结构中,Unmarshal会将传入的对象键与Marshal使用的键(结构字段名称或其标记)进行匹配,希望使用精确匹配,但还要接受不区分大小写的匹配.
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.
推荐答案
不幸的是,标准json库当前不支持此功能.
Unfortunately this is not something currently supported by the standard json library.
根据 https://golang.org/pkg/encoding/json/#Unmarshal
Unmarshal将传入的对象键与Marshal使用的键(结构字段名称或其标记)进行匹配,更喜欢精确匹配,但也接受不区分大小写的匹配
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
无法关闭此行为.
这篇关于区分大小写的JSON Unmarshal结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!