Ram
Ram

Reputation: 731

how to construct json object using any json library/jar

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.

Upvotes: 1

Views: 1210

Answers (1)

Matt Goodrich
Matt Goodrich

Reputation: 5095

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"}}

Upvotes: 1

Related Questions