1

I just want to construct JSON object something like this:

"Root":{
  "c1": "v1"
}

I tried with the following code :

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public class Exe {

    public static void main(String[] args) throws JSONException {
        JSONObject object = new JSONObject("ROOT");
        object.put("c1", "v1");
        System.out.println(object.toString());
    }
}

with this code, I got the following exception:

Exception in thread "main" org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 1 of ROOT

I played with codehaus API, but I didn't find the solution, so can you please help me on this.

1
  • You can use json.org -> for java library. Its simple and usefull. You can create json object with same syntax in javascript. Example : String jsonStr = "{myKey1:'myValue1'}"; JSONObject object = new JSONObject(jsonStr ); Commented May 3, 2017 at 7:47

1 Answer 1

1

You need to create the JSONObject and then add the "Root": value key-value pair to the object. The constructor accepting a String where you have "Root" expects a complete JSON object as a String.

JSONObject requestedObject = new JSONObject();
JSONObject innerValue = new JSONObject();
innerValue.put("c1", "v1");
requestedObject.put("Root", innerValue);
System.out.println(requestedObject);

has been confirmed to produce:

{"Root":{"c1":"v1"}}

As an important additional note, the JSON object you request isn't a valid JSON object. In case you're interested, you can check for valid JSON with a JSON lint tool. A valid object is shown below.

{
    "Root":{
        "c1": "v1"
    }
}

Here's a quick snippet to confirm the statement about the constructor with a String.

JSONObject strConstr = new JSONObject("{\"Root\":{\"c1\":\"v1\"}}");
System.out.println(strConstr);

has been confirmed to produce:

{"Root":{"c1":"v1"}}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Matt, I'll try this
No problem @Creator! I'm glad I can help.

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.