2

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.

snøreven
  • 1,904
  • 2
  • 19
  • 39
  • Your explanation is difficult to follow I'm afraid. Can you clarify what you want to achieve? Is this what you want? http://stackoverflow.com/questions/11126793/golang-json-and-dealing-with-unexported-fields It allows a private struct with exported fields, so you can defined what you want to be accessed with getters/setters but export the whole struct. – minikomi Feb 03 '13 at 05:58
  • @minikomi: No, I want to export different fields for the Encoder than for the Decoder. Because the user should be able to see more fields than he is allowed to change. A very common task if you program an API. – snøreven Feb 03 '13 at 12:03

2 Answers2

0

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.

Dustin
  • 89,080
  • 21
  • 111
  • 133
  • Thanks for the answer. Ok, so there seems to be no other way. Unfortunately thats exactly what I absolutely do not want. I'm trying to modify the json package and add a "notencoding"/"notdecoding" tag now. – snøreven Feb 03 '13 at 12:12
0

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"`
}
snøreven
  • 1,904
  • 2
  • 19
  • 39