dszsajhd237437 2017-11-08 20:08
浏览 46
已采纳

在不涉及所有字段的情况下封送和封送JSON正文

I'm looking for a way to unmarshal a JSON body without having to specify targets for all fields. And then be a able to "remarshal" the body with implicit fields untouched.

Something like this would be good, but doesn't work as a expected: (https://play.golang.org/p/fnVOKrmiFj)

package main

import (
    "encoding/json"
    "fmt"
)

type Transaction struct {
    Field1  string                  `json:"field1"`
    X       map[string]interface{}  `json:"-"`
}

func main() {
    body := []byte(`{"field1": "value1", "field2": "value2"}`)
    fmt.Printf("%+v
", string(body))

    var unmarshalledTransaction Transaction
    json.Unmarshal(body, &unmarshalledTransaction)
    fmt.Printf("%+v
", unmarshalledTransaction)

    remarshalledTransaction, _ := json.Marshal(&unmarshalledTransaction)
    fmt.Printf("%+v
", string(remarshalledTransaction))    
}

Gives the output

{"field1": "value1", "field2": "value2"}
{Field1:value1 X:map[]}
{"field1":"value1"}

My expected result would be that unmarshalledTransaction contains the "leftover" fields in the X fields. And they are then restored when Marshalling again.

Can this be done?

  • 写回答

2条回答 默认 最新

  • dongshang5862 2017-11-08 21:33
    关注

    You would need to implement the MarshalJSON and UnmarshalJSON interfaces, and write your own logic to remap the fields to the appropriate spots:

    func (t *Transaction) MarshalJSON() ([]byte, error) {
        data := t.X
        data["field1"] = t.Field1
        return json.Marshal(data)
    }
    
    func (t *Transaction) UnmarshalJSON(data []byte) error {
        m := make(map[string]interface{})
        json.Unmarshal(data, &m)
        t.Field1 = m["field1"].(string)
        delete(m, "field1")
        t.X = m
        return nil
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类