为JSON编码器/解码器“发布”了不同的结构属性

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.

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"`
}

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.