如何动态更改结构的 json 标签? [英] How do I dynamically change the struct's json tag?

查看:28
本文介绍了如何动态更改结构的 json 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "reflect"
)

type User struct {
    ID   int64  `json:"id"`
    Name string `json:"first"` // want to change this to `json:"name"`
    tag  string `json:"-"`
    Another
}

type Another struct {
    Address string `json:"address"`
}

func (u *User) MarshalJSON() ([]byte, error) {
    value := reflect.ValueOf(*u)
    for i := 0; i < value.NumField(); i++ {
        tag := value.Type().Field(i).Tag.Get("json")
        field := value.Field(i)
        fmt.Println(tag, field)
    }
    return json.Marshal(u)
}

func main() {
        anoth := Another{"123 Jennings Street"}
    _ = json.NewEncoder(os.Stdout).Encode(
        &User{1, "Ken Jennings", "name",
             anoth},
    )
}

我正在尝试对结构进行 json 编码,但在此之前我需要更改 json 键...例如,最终的 json 应如下所示:

I am trying to json encode the struct but before I do I need to change the json key...eg the final json should look like:

{"id": 1, "name": "Ken Jennings", "address": "123 Jennings Street"}

我注意到 value.Type().Field(i).Tag.Get("json") 的方法,但是没有 setter 方法.为什么?以及如何获得所需的 json 输出.

I noticed the method for value.Type().Field(i).Tag.Get("json"), however there is no setter method. Why? and how do I get the desired json output.

此外,如何遍历所有字段,包括嵌入的另一个结构体?

Also, how do I iterate through all the fields, including the embedded struct Another?

https://play.golang.org/p/Qi8Jq_4W0t

推荐答案

它很笨拙,但是如果您可以将结构包装在另一个结构中,并使用新的进行编码,那么您可以:

It's kludgy, but if you can wrap the struct in another, and use the new one for encoding, then you could:

  1. 对原始结构进行编码,
  2. 将其解码到接口{}以获取地图
  3. 替换地图键
  4. 然后对地图进行编码并返回

因此:

type MyUser struct {
    U User
}

func (u MyUser) MarshalJSON() ([]byte, error) {
    // encode the original
    m, _ := json.Marshal(u.U)

    // decode it back to get a map
    var a interface{}
    json.Unmarshal(m, &a)
    b := a.(map[string]interface{})

    // Replace the map key
    b["name"] = b["first"]
    delete(b, "first")

    // Return encoding of the map
    return json.Marshal(b)
}

在操场上:https://play.golang.org/p/TabSga4i17

这篇关于如何动态更改结构的 json 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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