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

6
  • 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. Commented Sep 26, 2014 at 18:48
  • 1
    Write a toDictionary method. Commented Sep 26, 2014 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. Commented Sep 26, 2014 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" Commented Sep 26, 2014 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? Commented Sep 26, 2014 at 18:55

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.