2

I am trying to initiale a json a jsonArray but i am lost in doing it.

Where am i wrong and how do we initiale a json array

JSONArray template = 
            {
                  "header": "Colors",
                  "items": [
                      {"name": "red", "first": true, "url": "#Red"},
                      {"name": "green", "link": true, "url": "#Green"},
                      {"name": "blue", "link": true, "url": "#Blue"}
                  ],
                  "empty": false
                };
5
  • the above is a jsonobject having one JSONArray "items". Commented Mar 21, 2013 at 6:37
  • 1
    json array starts with[ and ends ] Commented Mar 21, 2013 at 6:37
  • First, that's a JSONObject, as comments already said. Secondly, you need to new the object- you can't create a java object like that. Commented Mar 21, 2013 at 6:43
  • i don't get your point Commented Mar 21, 2013 at 6:43
  • @yakusha this is jsonobject and it has a json array, you want like this then initialize it as jsonobject Commented Mar 21, 2013 at 6:44

4 Answers 4

1

You need to create a JSONObject of the template mentioned, which will automatically initialize the items.

try {
    String template = "{\"header\": \"Colors\", " +
        "\"items\": [ " +
        "{\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}, " +
        "{\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}, " +
        "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"}" +
        " ], \"empty\": false }";

    JSONObject jsonWithArrayInIt = new JSONObject(template); //JSONObject created for the template.
    JSONArray items = jsonWithArrayInIt.getJSONArray("items"); //JSONArray of items present inside the JSONObject.
    System.out.println(items.toString());
} catch (JSONException je) {
    //Error while creating JSON.
}
Sign up to request clarification or add additional context in comments.

Comments

0

instead of self formatting, I've been doing it with following way and it worked for me.

  function fillPolicydetails()
    {
    var clsPolicyDetails={}
      clsPolicyDetails.name="Sangeeta"
      clsPolicyDetails.technology=".net"
    return clsPolicyDetails;
    }




     $.ajax({
                type: "POST",
                url: url,
                data:  "{'policydetail':" + JSON.stringify(fillPolicydetails())+"}",    //finally here's the magic:
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (Result) {
                    successFunction(Result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    failureFunction(jqXHR, textStatus, errorThrown);
                }
            });

above code will generate json format for you and will send it as an object instead of raw strings

if any issues please let me know.

Comments

0

if template is your json array means holding more than one value then initialize like this :

JSONArray template = new JSONArray("
        [{
              "header": "Colors",
              "items": [
                  {"name": "red", "first": true, "url": "#Red"},
                  {"name": "green", "link": true, "url": "#Green"},
                  {"name": "blue", "link": true, "url": "#Blue"}
              ],
              "empty": false
            }]");

if items is json array and template is a json object holding items then do like this

JSONArray items=new JSONArray ("[
                      {"name": "red", "first": true, "url": "#Red"},
                      {"name": "green", "link": true, "url": "#Green"},
                      {"name": "blue", "link": true, "url": "#Blue"}
                  ]");


JSONObject template = new JSONObject();
template .put("sessionId",
                    new JSONString("Colors"));
template .put("items",
                    items);
template .put("empty",
                    new JSONBoolean(false));

Logic is correct sometimes its function name or class name will change according to different package. I am using com.google.gwt.json.client

Comments

0

Following is the proper way to initialize an JSONArray

public class TestJSON {

public static void main(String[] args) {
    JSONArray template = new JSONArray("[ {\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}," +
            " {\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}," +
            "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"} ]");

    System.out.println(template.toString());

    }
}

Following is the output:

[
    {
        "name": "red",
        "first": true,
        "url": "#Red"
    },
    {
        "link": true,
        "name": "green",
        "url": "#Green"
    },
    {
        "link": true,
        "name": "blue",
        "url": "#Blue"
    }
]

EDIT1:

You can use the following code to create your full JSON object..

    public static void main(String[] args) {
        JSONArray template = new JSONArray(
            "[ {\"name\": \"red\", \"first\": true, \"url\": \"#Red\"},"
                + " {\"name\": \"green\", \"link\": true, \"url\": \"#Green\"},"
                + "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"} ]");

        JSONObject object = new JSONObject();
        object.put("header", "Colors");
        object.put("empty", false);
        object.put("items", template);

        System.out.println(object.toString());
        }

Following is the output:

{
    "items": [
        {
            "name": "red",
            "first": true,
            "url": "#Red"
        },
        {
            "link": true,
            "name": "green",
            "url": "#Green"
        },
        {
            "link": true,
            "name": "blue",
            "url": "#Blue"
        }
    ],
    "empty": false,
    "header": "Colors"
}

EDIT2:

Following code can be used to generate the full JSON object without using string containing JSON data:

 public static void main(String[] args) {
    JSONArray template = new JSONArray();

    JSONObject obj = new JSONObject();
    obj.put("name", "red");
    obj.put("first", true);
    obj.put("url", "#Red");
    template.put(obj);

    JSONObject obj1 = new JSONObject();
    obj1.put("name", "green");
    obj1.put("link", true);
    obj1.put("url", "#Green");
    template.put(obj1);

    JSONObject obj2 = new JSONObject();
    obj2.put("name", "blue");
    obj2.put("link", true);
    obj2.put("url", "#Blue");
    template.put(obj2);

    JSONObject object = new JSONObject();
    object.put("header", "Colors");
    object.put("empty", false);
    object.put("items", template);

    System.out.println(object.toString());
    }

Following is the output of this program:

{
    "items": [
        {
            "name": "red",
            "first": true,
            "url": "#Red"
        },
        {
            "link": true,
            "name": "green",
            "url": "#Green"
        },
        {
            "link": true,
            "name": "blue",
            "url": "#Blue"
        }
    ],
    "empty": false,
    "header": "Colors"
}

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.