热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

protobuf.js将proto文件转换为JSON描述符,重复丢失

如何解决《protobuf.js将proto文件转换为JSON描述符,重复丢失》经验,为你挑选了1个好方法。

我正在使用Protobuf.js构建一个节点包,其中包含我们的协议,并为此包中定义的Proto消息提供编码和解码功能.我可以使用.proto文件(.proto文件的加载在运行时发生),但由于模块需要在客户端可用,我无法将.proto文件打包到我已解析的.js文件(使用browserify构建),我需要使用一种方法,在build.js中启用打包.

输入JSON描述符.

var jsOnDescriptor= require("./awesome.json"); // exemplary for node

var root = protobuf.Root.fromJSON(jsonDescriptor);

可以打包json文件(需要通过browserify解析).Proto Type Defintions也可以在.json中使用

我将.proto文件转换为.json文件,并使用我的示例数据进行了尝试.不幸的是,重复的领域失败了.

.proto文件看起来像这样:

message Structure {
    map  blocks = 1;
}

message Inner{
    int32 a = 1;
    int32 b = 2;
    bool c = 3;
}

message InnerArray{
    repeated Inner inners = 1;
}   

我将其翻译成此JSON描述符

{
  "nested": {
    "Structure": {
      "fields": {
        "blocks": {
          "type": "InnerArray",
          "id": 1,
          "map" : true,
          "keyType" : "int32"
        }
      }
    },
    "InnerArray" : {
        "fields": {
            "inners" : {
                "repeated" : true,
                "type" : "Inner",
                "id" : 1
            }
        }
    },
    "Inner" : {
        "fields" : {
            "a" : {
                "type" : "int32",
                "id" : 1
            },
            "b" : {
                "type" : "int32",
                "id" : 2
            },
            "c" : {
                "type" : "bool",
                "id" : 3
            }
        }
    }
  }
}

如果我没弄错的话,那里有一个字段的必需属性.

当我对我的示例数据进行编码和解码时,它会在重复的字段处停止:(注意地图工作正常).

{
  "blocks": {
    "0": {
      "inners": {}
    },
    ...

我还检查了我的root以了解加载类型的外观,它看起来与我的定义完全相同,除了重复丢失:

"InnerArray" : {
            "fields": {
                "inners" : {
                    "type" : "Inner",
                    "id" : 1
                }
            }
        },

如何在JSON描述符中正确定义重复字段?

如果有一种方法可以预先包含proto文件而不是在运行时加载它们,那么我可以用browserify包装它们,我也会接受它作为解决方案.



1> Strernd..:

浏览完代码后,我发现您无法在JSON描述符中设置必需.正确的方法是设置 "rule": "repeated"; 因为字段是用字段描述符设置的


推荐阅读
author-avatar
BigUncle
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有