doutan1905 2013-10-02 19:25
浏览 68
已采纳

json.RawMessage的元帅

Please find the code here http://play.golang.org/p/zdQ14ItNBZ

I am keeping JSON data as RawMessage, but cannot decode it out. I need the containing struct to be Marshalled and Unmarshalled, but I would expect still be able to get the JSON field.

code:

package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    Name string
    Id   int
    Json json.RawMessage
}
type Data2 struct {
    Name string
    Id   int
}


func main() {

    tmp := Data2{"World", 2}

    b, err := json.Marshal(tmp)
    if err != nil {
        fmt.Println("Error %s", err.Error())
    }
    fmt.Println("b %s", string(b))

    test := Data{"Hello", 1, b}
    b2, err := json.Marshal(test)
    if err != nil {
        fmt.Println("Error %s", err.Error())
    }

    fmt.Println("b2 %s", string(b2))

    var d Data
    err = json.Unmarshal(b2, &d)
    if err != nil {
        fmt.Println("Error %s", err.Error())
    }
    fmt.Println("d.Json %s", string(d.Json))

    var tmp2 Data2
    err = json.Unmarshal(d.Json, &tmp2)
    if err != nil {
        fmt.Println("Error %s", err.Error())
    }
    fmt.Println("Data2 %+v", tmp2)

}

out:

b %s {"Name":"World","Id":2}
b2 %s {"Name":"Hello","Id":1,"Json":"eyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0="}
d.Json %s "eyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0="
Error %s json: cannot unmarshal string into Go value of type main.Data2
Data2 %+v { 0}
  • 写回答

2条回答 默认 最新

  • duanne9313 2013-10-02 19:37
    关注

    the methods on json.RawMessage all take a pointer receiver, which is why you're not able to utilize any of them; you don't have a pointer.

    This "works" in the sense that it executes, but this is likely not the strategy that you want: http://play.golang.org/p/jYvh8nHata

    basically you need this:

    type Data struct {
        Name string
        Id   int
        Json *json.RawMessage
    }
    

    and then propagate that change through the rest of your program. What... what are you actually trying to do?

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

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路