JSON并处理未导出的字段

编程入门 行业动态 更新时间:2024-10-24 14:23:22
本文介绍了JSON并处理未导出的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

编码/ json不包含未导出的字段是否存在技术原因?如果不是,这是一个任意的决定是否可以有一个额外的后门选项(比如说'+')包括即使未提交?

要求客户端代码导出以获取这个功能感觉很不幸,特别是如果小写字母提供封装或者编组结构的决定比它们的设计迟得多。

人们如何处理这个问题?只需要导出所有内容?

另外,不输出字段名称会导致难以遵循建议的习惯用法。我认为如果结构X具有字段Y,则不能有访问器方法Y()。如果你想为Y提供接口访问权限,你必须为getter提供一个新的名字,不管你根据 golang/doc/effective_go.html#Getters

解决方案

有一个技术原因。 json库没有权力使用反射来查看字段,除非它们被导出。一个包只能在它自己的包中查看未导出类型的字段。为了处理你的问题,你可以做的是使用导出的域创建一个未导出的类型。如果传递给Json将不会出现问题,Json将解组成一个未导出类型,但它不会显示在API文档中。然后,您可以制作嵌入未导出类型的导出类型。然后,此导出类型需要实现 json.Marshaler 和 json.Unmarshaler 接口的方法。

注意:所有代码都未经测试,甚至可能无法编译。

type jsonData struct { Field1 string Field2 string } type JsonData struct { jsonData } // // json.Unmarshaller func(d * JsonData)UnmarshalJSON(b [] byte)错误{返回json.Unmarshal(b,& d.jsonData)} // Getter func(d * JsonData)Field1()string { return d.jsonData.Field1 }

Is there a technical reason why unexported fields are not included by encoding/json? If not and it is an arbitrary decision could there be an additional back door option (say '+') to include even though unexported?

Requiring client code to export to get this functionality feels unfortunate, especially if lower case is providing encapsulation or the decision to marshal structures comes much later than design of them.

How are people dealing with this? Just export everything?

Also, doesn't exporting field names make it difficult to follow suggested idioms. I think if a struct X has field Y, you can not have an accessor method Y(). If you want to provide interface access to Y you have to come up with a new name for the getter and no matter what you'll get something un-idiomatic according to golang/doc/effective_go.html#Getters

解决方案

There is a technical reason. The json library does not have the power to view fields using reflect unless they are exported. A package can only view the unexported fields of types within its own package

In order to deal with your problem, what you can do is make an unexported type with exported fields. Json will unmarshal into an unexported type if passed to it without a problem but it would not show up in the API docs. You can then make an exported type that embeds the unexported type. This exported type would then need methods to implement the json.Marshaler and json.Unmarshaler interfaces.

Note: all code is untested and may not even compile.

type jsonData struct { Field1 string Field2 string } type JsonData struct { jsonData } // Implement json.Unmarshaller func (d *JsonData) UnmarshalJSON(b []byte) error { return json.Unmarshal(b, &d.jsonData) } // Getter func (d *JsonData) Field1() string { return d.jsonData.Field1 }

更多推荐

JSON并处理未导出的字段

本文发布于:2023-11-30 05:27:57,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!