JSON 和处理未导出的字段 [英] JSON and dealing with unexported fields

查看:17
本文介绍了JSON 和处理未导出的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

未导出的字段未包含在 encoding/json 中是否存在技术原因?如果不是,并且这是一个任意决定,即使未导出,是否还有其他后门选项(例如+")可以包含在内?

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?

此外,不导出字段名称会使遵循建议的习语变得困难.我认为如果结构 X 具有字段 Y,则您不能拥有访问器方法 Y().如果你想提供对 Y 的接口访问,你必须为 getter 想出一个新名称,无论你得到什么,根据 http://golang.org/doc/effective_go.html#Getters

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 http://golang.org/doc/effective_go.html#Getters

推荐答案

有技术原因.json 库无权使用反射查看字段,除非它们被导出.一个包只能查看自己包内类型的未导出字段

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

为了解决您的问题,您可以做的是使用导出字段制作未导出的类型.如果没有问题地传递给 Json,它将解组为未导出的类型,但它不会出现在 API 文档中.然后,您可以创建嵌入未导出类型的导出类型.这个导出的类型需要方法来实现 json.Marshalerjson.Unmarshaler 接口.

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 和处理未导出的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆