简体   繁体   English

Java对象到JSON的转换

[英]Java Object to JSON Conversion

I have a Java object as below 我有一个Java对象,如下所示

    public class Command {
    private String cmd;
    private Object data;
}

I want JSON Conversion of this Object to look as below 我希望此对象的JSON转换如下所示

{"cmd":"getorder","data":{"when":"today"}}

How do I do this without changing the Class definition? 如何在不更改类定义的情况下执行此操作?

I know how to use GSON or Jackson library. 我知道如何使用GSON或Jackson库。 I am having trouble assigning values to or initializing (Object) data above, so that it properly converts to {"when":"today"} when I use those libraries. 我在为上面的数据分配值或初始化(对象)数据时遇到麻烦,因此当我使用这些库时,它可以正确转换为{“ when”:“ today”}。

Thanks 谢谢

您可以尝试使用Gson库,它非常易于使用,并且还可以执行反向操作

Depending on your needs you might consider to add a handwritten json formatter for your class (of yourse this interferes with your demand to not change the class definition) but in fact it gives you max flexibility without 3rd party dependencies. 根据您的需要,您可以考虑为您的班级添加一个手写的json格式器(这会干扰您不更改班级定义的要求),但实际上,它为您提供了最大的灵活性,而无需第三方依赖。 If you strictly let all your Objects overwrite toString() to give json formatted string representation you could eg 如果严格让所有对象覆盖toString()以提供json格式的字符串表示形式,则可以例如

String toString() {
    StringBuffer result = new StringBuffer();
    result.add("{ \"cmd\":" + this.cmd);
    result.add(",");
    result.add( \"data\":" + data.toString());
    result.add("}");
    return result.toString();
}

In case your need to not change the class definition appears more important than the mentioned advanteges there is aa nice json library avaialble on code.google.com named "simple json" ( https://code.google.com/p/json-simple/ ). 万一您不需要更改类定义比上述优点更为重要,可以在code.google.com上使用一个名为“ simple json”的不错的json库( https://code.google.com/p/json-简单/ )。

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

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