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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?