gpt4 book ai didi

javascript - 如何使用 Protobuf.js 解码 proto 文件的 Json 格式?

转载 作者:搜寻专家 更新时间:2023-11-01 04:08:14 24 4
gpt4 key购买 nike

我想了解 ProtoBuf.js 是如何工作的?

ProtoBuf - https://github.com/dcodeIO/ProtoBuf.js

我的原型(prototype)文件 gameSetting.proto 看起来像:

message GameSettings {
required string gameName = 1;
repeated Category categories = 2;
}

message Category {
required int32 categoryId = 1;
required string categoryAbbreviation = 2;
required string categoryName = 3;
required string numberInSquad = 4;
required string numberInTeam = 5;
required string captain = 6;
}

在这里,我正在实现带有数据解码和编码的 JavaScript 代码:

  var ProtoBuf = dcodeIO.ProtoBuf;
var protoURL = '../_doc/protobuf/gameSettings.proto';
var dataURL = '../xmlapi?type=game-settings&competitionid=1&outputtype=text';
var builder = ProtoBuf.loadProtoFile( protoURL, function(err, builder) {

// WE CAN ALSO TRY USING JSON FORMAT FOR THE PROTO FILES:
// https://github.com/dcodeIO/ProtoBuf.js/wiki/Builder#using-json-without-the-proto-parser

// encoding test
var GS_build = builder.build( 'GameSettings' );
var GS = new GS_build({
"gameName": "games Test 2015",
"categories": [{
"categoryId": 1,
"categoryAbbreviation": "GK",
"categoryName": "Goalkeeper",
"numberInSquad": "2-2",
"numberInTeam": "1-1",
"captain": "0-1"
}]
});


// encode various types to test
var GS_buffer = GS.encode();
var GS_base64 = GS.encode64(); // this looks like something to use with AJAX
var GS_arrayBuffer = GS_buffer.toArrayBuffer();

// decoding test
var GS_buffer_decoded = GS_build.decode( GS_buffer );
var GS_buffer_decoded_raw = GS_buffer_decoded.toRaw();
var GS_base64_decoded = GS_build.decode64( GS_base64 );
var GS_base64_decoded_raw = GS_base64_decoded.toRaw();
var GS_arrayBuffer_decoded = GS_build.decode( GS_arrayBuffer );
var GS_arrayBuffer_decoded_raw = GS_arrayBuffer_decoded.toRaw();


// decoding AJAX test
$.get( dataURL, function( data ){
var GS = GS_build.decode( data );
});
});

The code // encoding test and // decoding test - works fine.

但是代码中有一些问题:

var GS = GS_build.decode( data ) 

我该如何解决?

最佳答案

这里的API是:

Message.decode(buffer:Uint8Array|ArrayBuffer|Buffer|string, encoding:string=)

with encoding 只有当 buffer 是一个字符串时才需要。因此,为了能够解码一大块数据,您必须确保它是 ArrayBuffer/Uint8Array,或者如果它是字符串,则提供正确的编码。

不过,不带任何选项使用 jQuery 的 $.get 可能会损坏数据。

另请参阅:https://github.com/dcodeIO/ProtoBuf.js/wiki/How-to-read-binary-data-in-the-browser-or-under-node.js%3F

关于javascript - 如何使用 Protobuf.js 解码 proto 文件的 Json 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30974386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com