node 怎么把buffer 转为json对象
答案:2 悬赏:80 手机版
解决时间 2021-01-25 10:07
- 提问者网友:孤凫
- 2021-01-25 04:32
node 怎么把buffer 转为json对象
最佳答案
- 五星知识达人网友:执傲
- 2021-01-25 04:47
前端传给服务器的只是json 格式的字符串,使用json_decode, mixed json_decode ( string $json [, bool $assoc ] ) var_dump(json_decode($json)); var_dump(json_decode($json, true)); 如果不带参数,则返回为对象 带上true时,返回数组 fore...
全部回答
- 1楼网友:孤独入客枕
- 2021-01-25 05:08
例子:
package org.protob;
import org.protob.w.helloworld;
import com.google.protobuf.invalidprotocolbufferexception;
import com.googlecode.protobuf.format.jsonformat;
import com.googlecode.protobuf.format.jsonformat.parseexception;
public class main {
public static void main(string[] args) throws exception {
main2(null);
main3(null);
main4(null);
}
//序列化 /返序列化
public static void main2(string[] args) throws invalidprotocolbufferexception {
//序列化
helloworld.builder builder=helloworld.newbuilder();
builder.setid(10);
builder.setstr("fx");
builder.setopt(20);
helloworld info=builder.build();
byte[] result=info.tobytearray() ;
//返序列化
helloworld msg = helloworld.parsefrom(result);
system.out.println(msg);
}
//protobuf转json
public static void main3(string[] args) throws invalidprotocolbufferexception {
//序列化
helloworld.builder builder=helloworld.newbuilder();
builder.setid(10);
builder.setstr("fx");
builder.setopt(20);
helloworld info=builder.build();
byte[] result=info.tobytearray() ;
//返序列化
helloworld hello = helloworld.parsefrom(result);
system.out.println(hello);
string jsonformat =jsonformat.printtostring(hello);
system.out.println(jsonformat);
}
//josn转protobuf
public static void main4(string[] args) throws parseexception {
helloworld.builder builder =helloworld.newbuilder();
string jsonformat = "{id:11,str:'xxx',opt:50}";
jsonformat.merge(jsonformat, builder);
system.out.println(builder.build());
}
}
proto文件 w.proto
package org.protob;
message helloworld
{
required int32 id = 1; // id
required string str = 2; // str
optional int32 opt = 3; //optional field
}
生成后的java类
// generated by the protocol buffer compiler. do not edit!
// source: w.proto
package org.protob;
public final class w {
private w() {}
public static void registerallextensions(
com.google.protobuf.extensionregistry registry) {
}
public interface helloworldorbuilder
extends com.google.protobuf.messageorbuilder {
// required int32 id = 1;
/**
*
required int32 id = 1;
*
* * id *
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯