-2

I'm trying to change encoding in json, and used both encoding/json and jsoniter. What I'm trying to accomplish is that if I supply a language, it will encode relevant field names as "name@lang" instead of "name". I've ben trying the following:

func registerFieldEncoder(field string) {
encoderFunc := func(p unsafe.Pointer, stream *jsoniter.Stream) {
    fmt.Print("test")
    str := *(*string)(unsafe.Pointer(p))
    newstr := str + "@sv"
    stream.WriteString(newstr)
}
isEmptyFunc := func(p unsafe.Pointer) bool {
    str := *(*string)(unsafe.Pointer(p))
    return len(str) == 0
}
jsoniter.RegisterTypeEncoderFunc(field, encoderFunc, isEmptyFunc)
jsoniter.RegisterFieldEncoderFunc("", field, encoderFunc, isEmptyFunc) }

The field represents the json tag, i.e.

`json:"field`

Is this possible to accomplish in go?

1 Answer 1

0

Unmarshall the json as map[string]interface{}

write a function that recurses into the map[string]interface looking for keys called "name"

copy these keys to "name@lang" in the same map and then delete the "name" key

Marshall the modified map out again

1
  • Thank you for the answer. I considered this, however I feel like it would create a lot of roundabouts between marshalling and unmarshalling(object -> json -> map -> modify -> json). I know it is possible to accomplish this in C# as the JSON library allows quite a lot of leeway, but I couldn't manage it in GO; perhaps forking the json library is also a possibility. Nov 30, 2018 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.