-2
{
    "users":[ {
            "user":"hi","password":"hi"
        }, {
            "user":"test","password":"test"
        }
    ]   
}

How to parse this type of JSON Objects? Please help..

3
  • Check out this link!
    – Rahul
    Apr 30, 2013 at 4:25
  • SO is not a replacement for search Apr 30, 2013 at 4:28
  • 2
    @ArunPJohny - In that case, why would you post an answer and encourage it all the more?
    – Rahul
    Apr 30, 2013 at 4:30

3 Answers 3

1

You need to use a json library like gson, jsonlib or jackson.

JSONObject: it is a hash object like Map where key value pairs are used

JSONArray: It is a collection of objects like List

0

JSONObject works like a map with key-value pairs. Eg. Code looks like below :

JSONObject obj=new JSONObject();
  obj.put("name","Hello");
  obj.put("nickname","Hi");
  StringWriter out = new StringWriter();
  obj.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);

JSONArray works like a list , Eg, code below:

JSONArray list = new JSONArray();
  list.add("Hello");
  list.add(new Integer(100));
  System.out.print(list);
0

You can differentiate the JSONArray & JSONObject as below:

JSONArray

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values.

[        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

    {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

    {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

  ]

JSONObject

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.

  {"bindings": [

    {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

    {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

    {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
 };

You can parse the JSONObject as below:

  JSONObject JsonObject = new JSONObject(json);
  JSONArray JsonArray_ = JsonObject .getJSONArray("users");
  for (int i = 0; i < numberOfItems; i++) {
     JSONObject record= JsonArray_photo.getJSONObject(i);    
     parsedObject.user = record.getString("user"); //its the same for all fields 
     parsedObject.password = record.getString("password");
     map.add(parsedObject);
   }

Not the answer you're looking for? Browse other questions tagged or ask your own question.