简体   繁体   中英

Initialse a jsonArray java

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

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

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 got from the JSONObject.

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

    }catch(JSONException je){
        //Error while creating JSON.
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM