1

Say I want to make the following JSON

{
    "key" : "1234",
    "request" : "info",
    "info" : {
        "type" : "user",
        "login" : {
            "username" : "some_username",
            "password" : "some_password"
        }
    }
}

Currently, this is how I'm achieving it

//Construct the JSON
JSONObject json = new JSONObject();
JSONObject info_json = new JSONObject();
JSONObject login_info = new JSONObject();           
try
{
    login_info.put("username", "some_username");
    login_info.put("password", "some_password");

    info_json.put("type", "user");
    info_json.put("login", login_info);

    json.put("key", "1234");
    json.put("request", "info");
    json.put("info", info_json);
}
catch (Exception e) 
{
    e.printStackTrace();  
    System.out.println("JSON could not be made");
}

It seems there should be a better way of doing this instead of making more JSONObjects, and placing them in a main JSON Object. Is there a better way to construct these on the fly than the method I am using?

Thanks in advance for any help!

4
  • Frankly, for something this simple, I don't even bother using the JSON classes and just print the json straight to stdout (or wherever your destination is). Commented Apr 29, 2013 at 19:49
  • 2
    Gson is the answer. Commented Apr 29, 2013 at 19:49
  • you could just load it as one String. Commented Apr 29, 2013 at 19:52
  • 1
    Well, my use case isn't always this simple, just wanted a simple example on here instead of having a 300 line example of nested JSONObjects @Edward Falk Commented Apr 29, 2013 at 19:54

1 Answer 1

1

If you work a lot with JSON data I would really recommend that you use Gson or Jackson. It's a lot more convenient and both of the libraries have very good support for converting to and from Java objects (which is a lot less messy and error prone than manually building your JSON through JSONObjects).

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

2 Comments

IMHO I've found Gson to be very easy to use
Gson and Jackson are very similar in functionality and they're almost interchangeable.

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.