草庐IT

json - Golang : Protobuff generated Struct is not decoding child attribute for json. 解码

coder 2024-07-10 原文

我有一个结构体正在与 protobuff 序列化器一起使用并且运行良好。

这个结构是由 protobuff 生成的,因此它有很多方法,比如 Unmarshal 等。

type Flight struct {
    FlightNo string  `json:"flightno, omitempty"`
    Carrier string   `json:"carrier, omitempty"`
}
func (m *Flight) Unmarshal(data []byte) error {
    l := len(data)
    iNdEx := 0
    for iNdEx < l {
        preIndex := iNdEx
        var wire uint64
        for shift := uint(0); ; shift += 7 {
            if shift >= 64 {
                return ErrIntOverflowFlight
            }
            if iNdEx >= l {
                return io.ErrUnexpectedEOF
            }
            b := data[iNdEx]
            iNdEx++
            wire |= (uint64(b) & 0x7F) << shift
            if b < 0x80 {
                break
            }
        }
    }
 // some more code
}

然后我想为这个航类信息添加额外的字段,

type FlightMeta struct {
    Source string `json:"source, omitempty"`
    Destination string `json:"destination, omitempty"`
}

然后我结合了这两个结构,

type CombinedFlight struct {
    Flight
    FlightMeta

}

type ResponseFlight struct {
    OnwardFlights  []CombinedFlight  `json:"onwardflights, omitempty"`
    ReturnFlights  []CombinedFlight  `json:"returnflights, omitempty"`
    Error string  `json:"error, omitempty"`
}

所以当我读取一些数据时,比如,

str "= `{"onwardflights": [{"flightno": "537", "carrier": "AI", "source": "BOM", "destination": "DEL"}], "error": "false"}`
respFlight = new(ResponseFlight)

err = json.Unmarshal([]byte(str), &respFlight)

fmt.Println("flightno:", respFlight.OnwardFlights[0].FlightNo, "flight source", respFlight.OnwardFlights[0].Source)

#prints "flightno:537 flight source:

它不打印第二个结构的值,因为按照我的说法,这没有正确解码。

但是当我手动设置属性并编码(将其编码为 json)时,这工作正常。 有线索吗?

最佳答案

尝试这样做

        type CombinedFlight1 struct {
            Flight
            FlightMeta

        }


        type CombinedFlight2 struct {
            Flight
            FlightMeta

        }

        type ResponseFlight struct {
           OnwardFlights  []CombinedFlight1  `json:"onwardflights, omitempty"`
           ReturnFlights  []CombinedFlight2  `json:"returnflights, omitempty"`
           Error string  `json:"error, omitempty"`
        }

它会很好地工作,如果你想编码,你必须创建两个不同的结构。如需更多了解,请参阅这篇文章

访问Initialize nested struct definition in Golang if it have same objects

关于json - Golang : Protobuff generated Struct is not decoding child attribute for json. 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851428/

有关json - Golang : Protobuff generated Struct is not decoding child attribute for json. 解码的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  3. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  4. ruby-on-rails - Rails 渲染带有驼峰命名法的 json 对象 - 2

    我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'

  5. ruby - 使用 JSON gem 将自定义对象转换为 JSON - 2

    我正在学习如何使用JSONgem解析和生成JSON。我可以轻松地创建数据哈希并将其生成为JSON;但是,在获取一个类的实例(例如Person实例)并将其所有实例变量放入哈希中以转换为JSON时,我脑袋放屁。这是我遇到问题的例子:require"json"classPersondefinitialize(name,age,address)@name=name@age=age@address=addressenddefto_jsonendendp=Person.new('JohnDoe',46,"123ElmStreet")p.to_json我想创建一个.to_json方法,这样我就可以获

  6. ruby-on-rails - 如何使用驼峰键名称从 Rails 返回 JSON - 2

    我正在构建一个带有Rails后端的JS应用程序,为了不混淆snake和camelcases,我想通过从服务器返回camelcase键名来规范化这一切。因此,当从API返回时,user.last_name将返回user.lastName。我如何实现这一点?谢谢!编辑:添加Controller代码classApi::V1::UsersController 最佳答案 我的方法是使用ActiveModelSerializer和json_api适配器:在你的Gemfile中,添加:gem'active_model_serializers'创建

  7. ruby-on-rails - 如何将数组输出为 JSON? - 2

    我有以下内容:@array.inspect["x1","x2","adad"]我希望能够将其格式化为:client.send_message(s,m,{:id=>"x1",:id=>"x2",:id=>"adad"})client.send_message(s,m,???????)如何在????????中获得@array输出?空间作为ID?谢谢 最佳答案 {:id=>"x1",:id=>"x2",:id=>"adad"}不是有效的散列,因为您有键冲突它应该是这样的:{"ids":["x1","x2","x3"]}更新:@a=["x1

  8. ruby - 使用 jbuilder 创建具有动态哈希键的 JSON - 2

    这里我想输出带有动态组名的json而不是单词组@tickets.eachdo|group,v|json.group{json.array!vdo|ticket|json.partial!'tickets/ticket',ticket:ticketend}end@ticket是这样的散列{a:[....],b:[.....]}我想要这样的输出{a:[.....],b:[....]} 最佳答案 感谢@AntarrByrd,这个问题有类似的答案:JBuilderdynamickeysformodelattributes使用上面的逻辑我已经

  9. ruby - 展平嵌套的 json 对象 - 2

    我正在寻找一种将“json”散列展平为展平散列但将路径信息保留在展平键中的方法。例如:h={"a"=>"foo","b"=>[{"c"=>"bar","d"=>["baz"]}]}flatten(h)应该返回:{"a"=>"foo","b_0_c"=>"bar","b_0_d_0"=>"baz"} 最佳答案 这应该可以解决您的问题:h={'a'=>'foo','b'=>[{'c'=>'bar','d'=>['baz']}]}moduleEnumerabledefflatten_with_path(parent_prefix=nil)

  10. ruby-on-rails - 如何计算 Ruby/Rails 中 JSON 对象的数量 - 2

    Ruby中如何“一般地”计算以下格式(有根、无根)的JSON对象的数量?一般来说,我的意思是元素可能不同(例如“标题”被称为其他东西)。没有根:{[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]}根包裹:{"posts":[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]} 最佳答案 首先,withoutroot代码不是有效的json格式。它将没有包

随机推荐