不同的结构属性“published”用于JSON编码器/解码器。

huangapple go评论85阅读模式
英文:

Different struct attributes "published" for JSON Encoder/Decoder

问题

我需要通过JSON导出一些大的结构体,并返回JSON字符串以更新它的某些属性。

让我们有以下结构体:

type House struct {
    Name   string  `json:"name"`
    Rooms  int     `json:"rooms_count"`
    Owner  *Owner  `json:"-"`
}

使用encoding/json对其进行编码将得到一个JSON字符串,如下所示:

{"name":"some name", "rooms_count":5}

现在我得到了这个JSON字符串:

{"name":"some other name", "rooms_count":7, Owner:{something...}}

用户想要更改每个属性。Owner是不允许的,因为它没有被导出。但是我只想允许更改rooms_count。有没有办法在Encoder中指定某些属性应该被导出,但不被Decoder使用?手动编写所有这些检查将非常不愉快。

英文:

I need to export some large structs via JSON, and take back JSON strings for updating only some of it's attributes.

Let's have following struct:

type House struct {
    Name   string  `json:"name"`
    Rooms  int     `json:"rooms_count"`
    Owner  *Owner  `json:"-"`
}

Encoding that with encoding/json will result in a JSON string like

{"name":"some name", "rooms_count":5}

I now get this JSON string:

{"name":"some other name", "rooms_count":7, Owner:{something...}}

The user wants to change every attribute. Owner is not allowed, because it's not exported. But I only want to only permit changes of rooms_count. Is there any way of saying that some attributes should be exported with the Encoder, but not be used by the Decoder? Having to write all these checks manualy would be very unpleasant.

答案1

得分: 0

在你的具体情况下,只需将其解组到一个新的结构体,并执行currentStruct.Rooms = newStruct.Rooms就是你想要的。

对于这种自定义的编组方式,没有一种完全直接的方法来实现。你能得到的最好的方法是使用两个具有不同标签的相同结构体,并使用一些反射来在它们之间进行转换。

英文:

In your exact case, simply unmarshalling to a new struct and doing a currentStruct.Rooms = newStruct.Rooms is exactly what you want.

For that type of custom marshalling, there's not a totally straightforward way to do it. The best you could get is two identical structs with different tags for different occasions and a bit of reflection to perform the conversion between them.

答案2

得分: 0

我为encoding/json包创建了一个补丁,并打开了一个

它只是为结构体添加了两个标签选项,用于分别在EncoderDecoder中忽略结构体字段。以下是一个示例,其中两个字段都被编码/导出,但只有Name字段被解码/更新:

type House struct {
    Name    string    `json:"house_name"`
    PubDate time.Time `json:"pub_date,nodecode"`
}
英文:

I created a patch for the encoding/json package and opened a ticket.

It just adds 2 tag options for structs for ignoring struct fields in the Encoder and Decoder separately. Example where all two fields are encoded/exported, but only Name is getting decoded/updated:

type House struct {
    Name    string    `json:"house_name"`
    PubDate time.Time `json:"pub_date,nodecode"`
}

huangapple
  • 本文由 发表于 2013年2月3日 06:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/14667281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定