Thrift无法从json反序列化为java对象 [英] Thrift can not deserialize from json to java object

查看:910
本文介绍了Thrift无法从json反序列化为java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从以下thrift对象生成了一个java对象:

I generated a java object from the following thrift object:

struct Account {
    1: required string accountType,
    2: bool accountActive,
}

我写了一个试用的java代码将java对象序列化为json字符串,然后将json字符串反序列化为java对象。我可以成功序列化但无法反序列化。

I wrote a java code trying to serialize java object to json string and then deserialize the json string back to java object. I can serialize successfully but failed to deserialize.

    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory());

    Account a1 = new Account();
    a1.setAccountType("P");
    a1.setAccountActive(true);

    String json = serializer.toString(a1);
    System.out.println(json);

    Account a2 = new Account();
    deserializer.deserialize(a2, json, "UTF-8");
    System.out.println(a2);
    System.out.println(a2.getAccountType());

它一直抛出以下异常:

Exception in thread "main" org.apache.thrift.protocol.TProtocolException: Required field 'accountType' was not present! Struct: Account(accountType:null, accountActive:false)

任何人都可以帮我弄清问题是什么?
提前致谢!

Can anyone help me figure out what's the issue? Thanks in advance!

推荐答案

SimpleJSONProtocol 从未旨在可以反序列化。改为使用 TJSONProtocol

The SimpleJSONProtocol was never intended to be deserializable. Use TJSONProtocol instead.

来自 http://wiki.apache.org/thrift/ThriftUsageJava


序列化为简单JSON

Serializing to "Simple" JSON

TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(work);

简单JSON协议产生适合AJAX或脚本语言的输出。它不保留Thrift的字段标签,也不能通过Thrift读回。

(强调我的)

这篇关于Thrift无法从json反序列化为java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆