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

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
gurusai
  • 153
  • 4
  • 16

3 Answers3

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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);
Vineet Singla
  • 1,609
  • 2
  • 20
  • 34
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);
   }
GrIsHu
  • 29,068
  • 10
  • 64
  • 102