0

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

BrownTownCoder
  • 1,312
  • 5
  • 19
  • 25
  • 1
    Check out GSON, or Jackson for object to JSON mapping tools. Or you could just override toString and do it manually. Tons of examples online. – proulxs Sep 26 '14 at 18:48
  • 1
    Write a [`toDictionary`](http://stackoverflow.com/a/26038784/581994) method. – Hot Licks Sep 26 '14 at 18:50
  • 1
    And go to json.org to learn the JSON syntax. It only takes 5-10 minutes to learn and stuff will make a lot more sense if you do. – Hot Licks Sep 26 '14 at 18:51
  • I am using Jackson. The issue isn't that. I have no trouble converting it to json. The issue is how do I assign value to data so that it converts to "when":"today" – BrownTownCoder Sep 26 '14 at 18:51
  • 1
    You'd make `data` be a Map `{ "when":"today" }`. You could instead do a custom class, but why pollute your app with more tiny classes? – Hot Licks Sep 26 '14 at 18:55
  • May be you can wrap `Command` with `CommandWrapper` class that uses a custom class for `data` having `when` property. Then you can convert `CommandWrapper` to Json instead.Another solution is to use Gson and make custom serializer for 'Command'. – M.Sameer Sep 27 '14 at 23:15

2 Answers2

2

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

M.Sameer
  • 3,072
  • 1
  • 24
  • 37
2

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/ ).

Matthias
  • 3,458
  • 4
  • 27
  • 46