简体   繁体   English

在Java中将对象序列化为json?

[英]Serialize an object to json in Java?

I am trying to serialize an instance of Campaign in Adwords API with gson at first with the code below: 我首先尝试使用gson将Adsons API中Campaign的实例序列化为以下代码:

Campaign c = new Campaign(); 
c.setName("beijing");
c.setId(23423L);
Gson gson = new Gson();
String json = gson.toJson(c);

and I get the exception that class Money declares multiple JSON fields named __equalsCalc. 我得到一个例外,Money类声明了多个名为__equalsCalc的JSON字段。 When I try to serialize the instance with json plugin of struts2 with the code below 当我尝试使用以下代码用struts2的json插件序列化实例时

String str = org.apache.struts2.json.JSONUtil.serialize(c);
System.out.println(str);

It works and output the correct result 它可以工作并输出正确的结果

{"adServingOptimizationStatus":null,"biddingStrategy":null,"budget":null,"campaignStats":null,"conversionOptimizerEligibility":null,"endDate":null,"frequencyCap":null,"id":23423,"name":"beijing","networkSetting":null,"servingStatus":null,"settings":null,"startDate":null,"status":null}

Then my question is that why can the json plugin of struts2 can serialize the instance correctly while gson cannot? 那么我的问题是为什么struts2的json插件可以正确序列化实例,而gson不能呢? Can I use the json plugin of struts2 to serialize objects to json since it is design to produce json result in struts2 not for this situation. 我可以使用struts2的json插件将对象序列化为json吗,因为它旨在在struts2中生成json结果,而不适合这种情况。

You can use the json plugin in struts2 to serialize your object manually to json string. 您可以在struts2中使用json插件将对象手动序列化为json字符串。 You can do that by calling the serialize static method. 您可以通过调用serialize static方法来实现。

String jsonString = JSONUtil.serialize(your_object);

Don't forget to include xwork-core jar in your classpath because it depends on it. 不要忘记在您的类路径中包含xwork-core jar,因为它依赖于它。

Sounds like either a bug in Gson or it is more particular/less robust. 听起来像是Gson中的错误,或更具体/更不可靠。 Without looking at the code for either it would be hard to know more. 如果不查看任一代码,将很难了解更多信息。

Personally I use Jackson for JSON to POJO transformations. 我个人使用Jackson进行JSON到POJO的转换。

Ultimately as long as the Structs2 plugin is available on your classpath I don't see why you couldn't leverage it's classes to handle JSON transformations. 最终,只要Structs2插件在您的类路径上可用,我就看不到为什么您不能利用它的类来处理JSON转换。 Ultimately JSON is a format therefore all JSON libraries need to produce commonly understandable data. 最终,JSON是一种格式,因此所有JSON库都需要产生通常可以理解的数据。

I had a similar problem and solved it by moving my use of SimpleDateFormat from the class level to inside a method. 我遇到了类似的问题,并通过将SimpleDateFormat的使用从类级别移到了方法内部来解决了。 GSON doesn't have to serialize SimpleDateFormat this way. GSON不必以此方式序列化SimpleDateFormat。

Hope this helps someone - 45 minutes of head banging for me! 希望这对某人有帮助-45分钟的头部撞击声为我服务! :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM