【问题标题】:Can't read the object back after write when set the parameter fieldNamesAsString_ is true with TJSONProtocol使用 TJSONProtocol 设置参数 fieldNamesAsString_ 为 true 时,写入后无法读取对象
【发布时间】:2016-07-20 17:21:58
【问题描述】:
CreateOrderRequest req = new CreateOrderRequest();

req.pid=1111;
req.name="xxx";

TMemoryBuffer mem_buf = new TMemoryBuffer(512);
TJSONProtocol bin_proto = new TJSONProtocol(mem_buf,true);

try
{
    req.write(bin_proto);
    System.out.println("====begin serial json=================");
    String jsonStr=mem_buf.toString("utf-8");
    System.out.println("after jasonprocol="+jsonStr);

    System.out.println("====begin deserial json=================");
    CreateOrderRequest req2 = new CreateOrderRequest();
    TMemoryBuffer mem_buf2 = new TMemoryBuffer(512);  
    byte[] data = jsonStr.getBytes();
    mem_buf2.write(data);

    TJSONProtocol bin_proto2 = new TJSONProtocol(mem_buf2,true);
    req2.read(bin_proto2);
    System.out.println("after de jasonprocol pid="+req.pid);
    System.out.println("after de jasonprocol name="+req.name);
}
catch(Exception e)
{
    System.out.println(e);
}

输出:

====begin serial json=================

after jasonprocol={"pid":{"i32":1111},"uid":{"i32":0},"corpId":  {"i32":0},"sharePriceE6":{"i64":0},"shareCount":{"i32":0},"totalPriceE6":{"i64":0},"bankcardId":{"i32":0},"name":{"str":"xxx"},"isAnonymous":{"tf":0},"expectIncomeE6":{"i64":0},"clientId":{"i32":0},"totalAmtE6":{"i64":0},"subSrc":{"str":""}}
====begin deserial json=================

org.apache.thrift.protocol.TProtocolException: Unexpected character:p

问题

如果fieldNamesAsString_没有设置为true,那么jasonStr变成{"1": {"i32":1111},"2":{"i32":0},"3":{"i32":0},...可以写回CreateOrderRequest,我觉得不合理。

你可以将一个对象写入一个json str,但不能读回?

【问题讨论】:

    标签: java thrift


    【解决方案1】:

    fieldNamesAsString 参数产生完全相同的效果:只写 JSON 格式。按照设计,您无法使用 Thrift 读取这种 JSON。

    所以本质上这有点类似于this issue,尽管不是完全相同的问题。

    您可以将对象写入 json str,但不能读回?

    是的,这就是这里的意图。显然有些人有它的用例。

    进一步阅读:

    【讨论】:

    • 感谢您的回答,但我认为实现反序列化方法不会很复杂,为什么不这样做呢?因为 TField 存储了 thriftId 和 fiedName,
    • @robin。 “我认为实现起来不会很复杂”——这是开源的,所以开火吧! You're more than welcome to provide a pull request.
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多