我需要根据上级(Type字段)中字段值中的变量实现自定义解组逻辑(VerifyingKey字段).我可以将情况分解如下(源自Unmarshal remaining JSON after performing custom unmarshalling)

type SingleKey struct {
  Type          string          `json:"type"`
  Others OtherFields   `json:"wrapped_fields"`
}

type OtherFields struct {
  FQDN         string          `json:"fqdn"`
  Address      string          `json:"address"`
  Nonce        int64           `json:"nonce"`
  Challenge    []byte          `json:"challenge"`
  NetworkID    string          `json:"network_id"`
  VerifyingKey []PublicKey     `json:"verifying_key"`
  Signature    []byte          `json:"signature"`
}

// Interface for Public Key
type PublicKey interface {
  // Methods specific to public key functionality
}

// Example concrete implementations (replace with your actual types)
type RsaPublicKey struct {
  PublicKey
  // ... (fields specific to RSA public key)
}

type EcdsaPublicKey struct {
  PublicKey
  // ... (fields specific to ECDSA public key)
}

我try 过很多替代方案,但我无法找到解决方案.

推荐答案

SingleKey个实现自定义解送器:


type singleKeyMarshal struct {
  Type          string          `json:"type"`
  Others      otherFieldsMarshal `json:"wrapped_fields"`
}

type otherFieldsMarshal struct {
  FQDN         string          `json:"fqdn"`
  Address      string          `json:"address"`
  Nonce        int64           `json:"nonce"`
  Challenge    []byte          `json:"challenge"`
  NetworkID    string          `json:"network_id"`
  VerifyingKey []json.RawMessage     `json:"verifying_key"`
  Signature    []byte          `json:"signature"`
}

func (s *SingleKey) UnmarshalJSON(in []byte) error {

  var sm singleKeyMarshal
  if  err:=json.Unmarshal(in,&sm); err!=nil {
    return err
  }
  // Copy all fields from sm to s
  switch sm.Type {
     // Deal with unmarshaling the public keys
     case "RSA": 
       // This depends on how it is marshaled. If it is rsa.PublicKey:
       key:=[]rsa.PublicKey{}
       if err:=json.Unmarshal(sm.Others.VerifyingKey,&key); err!=nil {
           return err
       }
       s.Others.VerifyingKey=key
       
  }
}

Json相关问答推荐

仅在通过Jolt输入时才级联Json的值

嵌套自定义解组

try 将文本标记放置在条形图上的同一高度

JOLT将对象名作为新属性添加到主体中

Jolt将键和值转换为单独的数组集

使用Jolt库对多个数组进行嵌套循环

来自json的可分析的构建报告

如何在Swift中使用JSON编码器的泛型

使用 jolt 变换展平嵌套 JSON - 非常复杂

Moshi:序列化 List 时出现问题

展平多个数组以保持顺序

jolt 通配符如何用于 RHS?

用powershell条件解析json文件的数组对象

如何使用 Newtonsoft.Json 反序列化 JSON 数组

Retrofit 2.0 如何解析嵌套的 JSON 对象?

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

请求返回字节,我无法解码它们

如何在spark 上将json字符串转换为数据帧

通过 JSON 发送 64 位值的公认方式是什么?

春天:返回@ResponseBodyResponseEntity>