Access JSON data without field name - android

I have a JSON data which is accessible through a link like http://192.55.23.210:8085/Services/getFriends?userId=xyz which returns an array like ["xyz","abc"]. How to access these objects

You can get the field names without having to know them using names(int) method of JSONObject class, and then access them:
public void getFieldNames(JSONArray jsonArray) {
List<String> fieldNames = new ArrayList<String>;
try {
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
fieldNames[i] = jsonObject.names(i);
}
} catch (Exception e) {
Log.e("ConnectToDatabase->getJsonData", "Error Parsing JSON Data "
+ e.toString());
}
}

JSONParser parser=new JSONParser();
String s="[\"xyz\",\"abc\"]";
try {
JSONArray jsonarray=(JSONArray)parser.parse(s);
for (Object object : jsonarray) {
System.out.println((String)object);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

How to get 2 json objects at once?

I'm using volley to get json object, I'm getting data like this
{"resultUser":19}
{"resultUser2":13}
How to get either the second one (resultuser2) or both?
try {
JSONObject o = new JSONObject(response);
String data = (String) o.get("resultUser2");
if (!data.equals("")) {
Toast.makeText(getApplicationContext(), "user2 id" + data, Toast.LENGTH_LONG).show();
//UserDetailsActivty.this.finish();
} else {
Toast.makeText(getApplicationContext(), "Ohh! Sorry,,Signing Up Failed ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
you can use JsonArray to iterate through all the jsonobjects like this
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.get(i);
//do whatever you want to do with the data
}
} catch(Exception e) {
}

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

How to put json array in json object

This is code which I'm using:
#Override
protected String doInBackground(String... arg0) {
String yourJsonStringUrl = "GetCalender_Events";
JsonParser jParser = new JsonParser();
json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.
My array looks like this:
{
"ContactList": [
{
"Column1": "22-05-2017",
"Event_Name": "Garba Compition",
"Description": "School organized garba compition"
},
{
"Column1": "24-05-2017",
"Event_Name": "Mahendi Compition",
"Description": "Mahendi compition"
}
]
}
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:
JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
#. Then parse ContactList and its item as below:
#Override
protected void onPostExecute(String strFromDoInBg) {
JSONArray jsonArray = json.getJSONArray("ContactList");
for (int i = 0; i < jsonArray.length(); i++) {
try
{
JSONObject c = jsonArray.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put(jsonarray);
} catch(JSONException e){
e.printStackTrace();
}
You get the values
JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
JSONObject song = songobj.getJSONObject(i);
String column=song.getString("Column1");
String name=song.getString("Event_Name");
String desc=song.getString("Description");
ldatosAgenda.add(new DatosAgenda(column,name,desc));
}
}

how to parse JSON array (Language array )?

I want to fetch string values from a JSON-array and set it to a spinner in Android. How can I
do this?
`{"languages":["English","Hindi","Punjabi","",""]} `languages":["English","Hindi","Punjabi","",""]}
You can parse your JSONARRAY like this
if (jsonResultArry != null) {
for (int i = 0; i < jsonResultArry.length(); i++) {
try {
JsonObject jsonPblm = jsonResultArry.getJSONObject(i);
pblmId = jsonPblm.getString("id");
ticketDate = jsonPblm.getString("ticket_date");
pblmName = jsonPblm.getString("description");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

ANDROID : How to use org.json.JSONArray in for loop

I use library JsonHttpResponseHandler
and this my code
Data JSON is =
[{"id":"4","2":"123","phone":"123","1":"Shin","0":"4","name":"Shin"},{"id":"5","2":"555","phone":"555","1":"Wolf","0":"5","name":"Wolf"},{"id":"6","2":"666","phone":"666","1":"Lunar","0":"6","name":"Lunar"}]
And this my code =
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONArray response)
Question is how can i use response data in for loop
Use below code ,
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jobj = response.getJSONObject(i);
String id = jobj.getString("id");
String two = jobj.getInt("2");
String phone = jobj.getInt("phone");
String one = jobj.getInt("1");
String zero = jobj.getInt("0");
String name = jobj.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
it is the same as array.
for(int i =0 ; i < response.length() ; i++){
JSONObject object = response.getJSONObject(i);
}
inside json array > jsonobject it is like using a List
for your reference : JSON Array iteration in Android/Java
String dataStr="[{\"id\":\"4\",\"2\":\"123\",\"phone\":\"123\",\"1\":\"Shin\",\"0\":\"4\",\"name\":\"Shin\"},{\"id\":\"5\",\"2\":\"555\",\"phone\":\"555\",\"1\":\"Wolf\",\"0\":\"5\",\"name\":\"Wolf\"},{\"id\":\"6\",\"2\":\"666\",\"phone\":\"666\",\"1\":\"Lunar\",\"0\":\"6\",\"name\":\"Lunar\"}]";
try {
JSONArray jsonStrs =new JSONArray("1111");
for(int i=0;i<jsonStrs.length();i++)
{
JSONObject jobj=jsonStrs.getJSONObject(i);
int id=jobj.getInt("id");
String phone=jobj.getString("phone");
//get other values
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources