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

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

问题描述

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

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



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



另外,不输出字段名称会导致难以遵循建议的习惯用法。我认为如果结构X具有字段Y,则不能有访问器方法Y()。如果你想为Y提供接口访问权限,你必须为getter提供一个新的名字,不管你根据 http://golang.org/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 http://golang.org/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并处理未导出的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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