2017-06-02 39 views
3

我使用Protobuf.js建立一個節點包,其中包含我們的協議,並提供編碼和解碼功能,在這個包中定義的原消息。我會很好的使用.proto文件(加載的.proto文件在運行時發生),但由於該模塊需要在客戶端使用,我不能將.proto文件打包到我解析的.js文件中(使用browserify構建),我需要使用一種方法,它可以在build.js中打包。protobuf.js原型文件轉換成JSON描述,反覆丟失

輸入JSON描述符。

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

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

json文件可以打包(需要通過browserify解決)。原型Defintions在以.json

也有可能我翻譯.proto文件轉換成一個以.json文件,並與我的示例數據試了一下。 不幸的是,它重複的領域失敗了。

的.proto文件看起來有點像這樣:

message Structure { 
    map <int32, InnerArray> 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 
      } 
     } 
    } 
    } 
} 

如果我沒有記錯的有一個字段的required屬性。

當我編碼和解碼停靠在現場重複我的示例數據:(請注意,地圖正常工作)。

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

我也檢查了我的根,找出負荷型的外觀和它看起來完全像我確定指標EXCEPT反覆丟失:

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

如何定義重複場在JSON描述符中正確嗎?

如果有一種方法可以預先包含proto文件,而不是在運行時加載它們,這樣我可以用browserify將它們包裝起來,我也會接受這種解決方案。

回答

2

通過代碼瀏覽後,我發現,你不能設置一個JSON描述必需的。 正確的方法是設置 "rule": "repeated"; 由於字段被設定爲一個Field Descriptor