dtw52353 2013-04-14 06:52
浏览 12
已采纳

Gos中具有非标准字段的结构数组上的MarshalJSON

I have the following types:

type IPFilePair struct {
    IP net.IP
    FileName string
}

type IPFilePairs []*IPFilePair

I'm trying to marshal the JSON of this using json.Marshal(sample_ipfilepairs) but because IP isn't a string, it changes it into something strange.

What is the proper way to make the JSON of this output IP as a string?

  • 写回答

1条回答 默认 最新

  • dongnuan7956 2013-04-14 09:29
    关注

    I think if you have access to the definition of IPFilePair, creating local typedef of net.IP that you add MarshanJSON() to is the way to go:

    package main
    
    import (
        "encoding/json"
        "net"
        "fmt"
    )
    
    type netIP net.IP
    
    type IPFilePair struct {
        IP netIP
        FileName string
    }
    
    type IPFilePairs []*IPFilePair
    
    func (ip netIP) MarshalJSON() ([]byte, error) {
        return json.Marshal(net.IP(ip).String())
    }
    
    func main() {
        pair1 := IPFilePair{netIP{127, 0, 0, 1}, "file1"}
        pair2 := IPFilePair{netIP{127, 0, 0, 2}, "file2"}
        sample_ipfilepairs := IPFilePairs{&pair1, &pair2}
    
        b, _ := json.Marshal(sample_ipfilepairs)
        fmt.Println(string(b))
    }
    

    This outputs:

    [{"IP":"127.0.0.1","FileName":"file1"},{"IP":"127.0.0.2","FileName":"file2"}]
    

    Of course, if you ever need to unmarshal that back into the same Go data structure, you'll want to implement UnmarshalJSON() on netIP using net.ParseIP.

    I'm certainly curious if anyone knows of an easier way to accomplish this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路