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) {
}
Related
I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm getting the above-mentioned error while trying to extract data from JSONObject.My objective is to extract the "transactionId" data and store it in a variable for future use.
What I have so far:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
/*txtJson.setText(result);*/
JSONObject jsonarray;
try {
jsonarray = new JSONObject(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My JSON Object is shown below:
{
"merchantId":"X",
"transactionId":"Y"
}
I'm new to Programming so any help would be appreciated.
Try this code
JSONArray jsonarray;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.optJSONObject(i);
Log.d("OutPut", mJsonObject.optString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if there is single ITEM in your JSONArray, you can remove forLoop.
And, if the response received is JSONObject then,
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
Log.d("OutPut", jsonObject.optString("transactionId"));
} catch (JSONException e) {
e.printStackTrace();
}
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
I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}
I want to parse a JSONArray that contains JSONObjects that have no names and whose (index int) positions within the array changes every week or so. I have attempted to parse a particular Object by it's attributes, but my parser only returns the last Object in the array.
How can i stop my loop when it reaches the object i want to parse and determine the int index of the object for further parsing.
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed == attributeiwant) {
//determine int index of object, so i can parse other attributes
//from same object
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use String.equals for comparing Strings instead of ==
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
// Get data from JsonObject
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use break; statement to break the loop, change your code to following:
int i = 0;
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
if(i<jArray.length())
{
//item found, use i as index of object.
}
else
//item not found.