BrownTownCoder
BrownTownCoder

Reputation: 1372

Java Object to JSON Conversion

I have a Java object as below

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

I want JSON Conversion of this Object to look as below

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

How do I do this without changing the Class definition?

I know how to use GSON or Jackson library. 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.

Thanks

Upvotes: 0

Views: 106

Answers (2)

Matthias
Matthias

Reputation: 3556

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. If you strictly let all your Objects overwrite toString() to give json formatted string representation you could e.g.

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 a a nice json library avaialble on code.google.com named "simple json" ( https://code.google.com/p/json-simple/ ).

Upvotes: 2

M.Sameer
M.Sameer

Reputation: 3151

You can try Gson library it's very easy to use and it can do the reverse operation as well

Upvotes: 2

Related Questions