// Reading json file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"boysquestion.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
// Try to parse JSON
String question = null;
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("category");
// JSONArray has x JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
question = jsonObj.getString("question");
int no_score = jsonObj.getInt("no_score");
int yes_score = jsonObj.getInt("yes_score");
int category = jsonObj.getInt("category");
Log.d("question boys", question);
tvBoyGirl.setText(question);
Log.d("random", question);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Json Response ,how to extract all things :
[{"category":1,"no_score":3,"question":"Does he ever send the first text of a conversation?","yes_score":1},{"category":1,"no_score":3,"question":"Does he reply with two or three word answers?","yes_score":1}]
Above is json response.. i want to extract each and everything..i.e category,no_score,yes_score and question..
i have tried
question = jsonObj.getString("question");
but i am not getting.. can anyone help me to extract.
Json object start with { and json array starts with [. In your case the json is an array.
So read it as an array instead of jsonobject.
i.e, you need to read it like below.
JSONArray jsonArray = new JSONArray(myjsonstring);
and iterate through the array and read each values.
Your for loop looks fine.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
question = jsonObj.getString("question");
int no_score = jsonObj.getInt("no_score");
int yes_score = jsonObj.getInt("yes_score");
int category = jsonObj.getInt("category");
tvBoyGirl.setText(question);
}
This is what i do after all things
ListQuestion();
tvQuestionText.setText(questions.get(i));
imUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
question_counter++;
tvQuestionCounter.setText(String.valueOf(question_counter));
if (!questions.isEmpty()) {
tvQuestionText.setText(questions.get(i));
if (yes_Score1.get(i) == -1) {
score = score - 1;
} else {
score = score + yes_Score1.get(i);
}
System.out.println(score);
Log.d("yes_per", String.valueOf(score));
counter++;
if (counter == 25) {
calculation();
}
}
}
});
imDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
question_counter++;
tvQuestionCounter.setText(String.valueOf(question_counter));
if (!questions.isEmpty()) {
tvQuestionText.setText(questions.get(i));
if (no_Score1.get(i) == -1) {
score = score - 1;
} else {
score = score + no_Score1.get(i);
}
Log.d("no_per", String.valueOf(score));
System.out.println(score);
counter++;
if (counter == 25) {
calculation();
}
}
}
});
}
Try this:
JSONArray jArray = new JSONArray(jsonString);
for(int i=0;i<jArray.length();i++)
{
JSONObject jObj = jArray.getJSONObject(i);
question = jObj.getString("question");
int no_score = jObj.getInt("no_score");
int yes_score = jObj.getInt("yes_score");
int category = jObj.getInt("category");
}
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();
}
Getting org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject..Where would be code went wrong?This is a program to get values from a live streaming ..complete code is given below..
JSON given
race: {
id: "44708",
track_id: "1",
track: "International",
starts_at: "2016-05-04 06:16:00",
finish_time: "1970-01-01 01:00:00",
heat_type_id: "123",
heat_status_id: "1",
speed_level_id: "5",
speed_level: "Nat Cadet & Junior",
win_by: "position",
race_by: "minutes",
duration: 10,
race_name: "Inkart National Heat",
race_time_in_seconds: 276.336
},
scoreboard: [
{
position: "1",
nickname: "Emily Linscott",
average_lap_time: "90.053",
fastest_lap_time: "60.490",
last_lap_time: "60.490",
rpm: "1225",
first_name: "Emily",
last_name: "Linscott",
is_first_time: "0",
total_races: "6",
racer_id: "1157509",
lap_num: "3",
kart_num: "63",
gap: ".000",
ambtime: "31728819591"
},
Code
protected JSONObject doInBackground(String... urls) {
JSONObject jsonObj = null;
Log.d("TAG","inside doInBackground..");
try {
URL url = new URL("http://daytonamk.clubspeedtiming.com/api/index.php/races/scoreboard.json?track_id=1&key=cs-dev" + kartNumber);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String result = convertInputStreamToString(inputStream);
parseResult(result);
Log.e("Message", "This is a message");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
String result = "";
{
while ((line = bufferedReader.readLine()) != null) {
builder.append( line);
}
return result;
}
}
private JSONObject parseResult(String result) {
JSONObject jsonObj = null;
if (result == null) {
Toast.makeText(Main_Activity.this, "Race not currently running", Toast.LENGTH_LONG).show();
} else {
try {
int number = 0;
jsonObj = new JSONObject("result");
JSONObject race = jsonObj.getJSONObject("race");
int durationInMins = race.getInt("duration");
String win_by = race.getString("win_by");
JSONArray scoreboard = jsonObj.getJSONArray("scoreboard");
Log.d("TAG", "Json value :" + scoreboard);
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
number = data.getInt("kart_num");
while (kartNumber == number) {
int gridPosition = data.getInt("position");
int gap = data.getInt("gap");
int lastLapTime = data.getInt("last_lap_time");
int bestLapTime = data.getInt("fastest_lap_time");
int raceInTime = race.getInt("race_time_in_seconds");
duration = durationInMins * 60 - raceInTime;
if (!(gridPosition == 1)) {
JSONObject dataPreviousGap = scoreboard.getJSONObject(i - 1);
int gapPrev = dataPreviousGap.getInt("gap");
gapUp = gap - gapPrev;
}
if (!(i == scoreboard.length() - 1)) {
JSONObject dataNext = scoreboard.getJSONObject(i + 1);
int gapNext = dataNext.getInt("gap");
gapDown = gapNext - gap;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObj) {
Intent myIntent = new Intent(Main_Activity.this, Display_Activity.class);
try {
JSONObject jsonObje = new JSONObject("result");
JSONArray scoreboard = jsonObje.getJSONArray("scoreboard");
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
myIntent.putExtra("GridPosition", data.getInt("position"));
myIntent.putExtra("LastLapTime", data.getInt("last_lap_time"));
myIntent.putExtra("MinutesToGo", duration);
myIntent.putExtra("BestLapTime",data.getInt("fastest_lap_time"));
myIntent.putExtra("GapUp", gapUp);
myIntent.putExtra("GapDown", gapDown);
}
Just as your logcat reads org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject
Log the response you are getting without parsing the data first. Then you may find out what data types you are dealing with eg: Strings, Integers, Floats,etc.
Post the response here for more help.
EDIT:
This line here jsonObj = new JSONObject("result");
Do this instead jsonObj = new JSONObject(result);
EDIT:
jsonObj = new JSONObject(result);
JSONObject obj = jsonObj.getJSONObject("race");
String id = obj.getString("id");
//do the same for all objects inside race
In order to combine 2 JSON arrays into one I use the following code (the input data areJSON arrays that wereconverted to a string)
private static String combineData(String Data, String data){
if (empty(data))
data = Data;
else { // need to append the data
try {
// first, convert the strings back to JSON objects
JSONObject jsonObj1 = new JSONObject(data); // existing data
JSONObject jsonObj2 = new JSONObject(Data); // new data
// Getting Array of Providers
String fieldName = context.getString(R.string.JSON_COMP_RECORDS);
// Second, get the array out of the JSON object
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
// Third, join them into one array
JSONArray arr = new JSONArray();
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record2.length(); i++) {
JSONObject c;
try {
c = record2.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
JSONObject json = new JSONObject();
json.put (context.getString(R.string.JSON_COMP_RECORDS), arr);
data = json.toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
return data;
}
I wonder if there is a way to do it more efficiently and get rid of the 2 loops?
How about this ? You can put JSONObject directly int another array
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
record2.put (c);
}
Hope this helps
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
record2.put(record1.getJSONObject(i));
}
I have a json response below.
{
"Table":[
{
"status":"failed",
"message":"Questions exausted for the Course"
}
]
}
I have to read status from the response. I have tried as below. But I am unable to read. Please help me guys.
if (result != null
&& !result.toLowerCase()
.startsWith("{\"status\":\"invalid") ) {
mysql.setLastRowCount(lastrowcount);
System.out.println("PE result in : " + result);
try {
JSONObject resultJson = new JSONObject(result);
JSONArray resultArray = resultJson.getJSONArray("Table");
String status=resultJson.getString("status");
System.out.println("Ravi Today "+status);
for (int i = 0; i < resultArray.length(); i++) {
try {
JSONObject tempJSONOBJECT = resultArray
.getJSONObject(i);
bean.setQuestion(tempJSONOBJECT
.getString(Constants.TAG_QUESTION));
bean.setOption1(tempJSONOBJECT
.getString(Constants.TAG_OPT1));
bean.setOption2(tempJSONOBJECT
.getString(Constants.TAG_OPT2));
bean.setOption3(tempJSONOBJECT
.getString(Constants.TAG_OPT3));
bean.setOption4(tempJSONOBJECT
.getString(Constants.TAG_OPT4));
bean.setOption5(tempJSONOBJECT
.getString(Constants.TAG_OPT5));
bean.setOption6(tempJSONOBJECT
.getString(Constants.TAG_OPT6));
bean.setOption7(tempJSONOBJECT
.getString(Constants.TAG_OPT7));
bean.setOption8(tempJSONOBJECT
.getString(Constants.TAG_OPT8));
bean.setRightAnswer(tempJSONOBJECT
.getString(Constants.TAG_ANSWER));
bean.setMedia(tempJSONOBJECT
.getString(Constants.TAG_MEDIA));
bean.setNumberOfOptions(tempJSONOBJECT
.getInt(Constants.TAG_NO_OPTIONS));
bean.setOptionMode(tempJSONOBJECT
.getString(Constants.TAG_MULTI_SELECT));
bean.setExplanation(tempJSONOBJECT
.getString(Constants.TAG_EXPLANATION));
bean.setQuestionID(tempJSONOBJECT
.getString(Constants.TAG_QID));
bean.setStatus(tempJSONOBJECT
.getString(Constants.TAG_STATUS));
bean.setMessage(tempJSONOBJECT
.getString(Constants.TAG_MESSAGE));
bean.setSubjectID(subjectid);
mysql.addToQuestionsTable(bean);
} catch (Exception _ex) {
_ex.printStackTrace();
}
if (tablehasrows == false) {
if (mysql.getTableRowCount("questionmastermain",
"SUBJECT_ID", subjectid) > 0) {
mysql.getNextQuestion(subjectid, false);
tablehasrows = true;
}
}
}
Try like below:
JSONObject resultJson = new JSONObject(result);
JSONArray resultArray = resultJson.getJSONArray("Table");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject b = venues.getJSONObject(i);
String status = b.getString("status");
}
Try this,,,
if(result!=null){
try {
JSONObject jsonObj =new JSONObject(result);
tablejsonarray=jsonObj.getJSONArray("Table");
for(int i=0;i<tablejsonarray.length();i++){
JSONObject l=tablejsonarray.getJSONObject(i);
status=l.getInt("status");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am having the response of one of webservice to get the feeds list and in that response i am getting the two array with the same name.
The problem is that i am not able get the details of the inner array i.e. "ProfileName", "ImageUrl" etc..
I have tried the json parsing.
Below is the response of JSON:
{"Status":true,
"result":
[
{"result": [
{"ProfileName":"followers5","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.png","Likes":3,"Hearts":2},
{"ProfileName":"followers5","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.mp4","Likes":0,"Hearts":0}
]}
,{"result":[
{"ProfileName":"followers6","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.png","Likes":0,"Hearts":2},
{"ProfileName":"followers6","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.mp4","Likes":0,"Hearts":0}
]}
]
}
I have tried as below:
class feedtask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
Httputils getmethod = new Httputils();
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j <= i; j++) {
JSONObject jo = ja.getJSONObject(j);
abcd.add(jo.getString("ProfileName"));
System.out.println("Profile Name--->"
+ jo.getString("ProfileName"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
Please help me out to get the details of the second array.
Any help will be appreciated.
Thank you.
try
{
JSONObject _JSONResponse=new JSONObject(response);
String status=_JSONResponse.getString("Status");
JSONArray _ArrayResponse=_JSONResponse.getJSONArray("result");
for(int i=0;i<_ArrayResponse.length();i++)
{
JSONArray object=_ArrayResponse.getJSONObject(i).getJSONArray("result");
for(int j=0;j<object.length();j++)
{
JSONObject jObject=object.getJSONObject(j);
ProfileName=jObject.getString("ProfileName") ;
VideoUrl=jObject.optString("VideoUrl") ;
Likes=jObject.optString("Likes") ;
Hearts=jObject.optString("Hearts") ;
Log.i(TAG,ProfileName +" "+VideoUrl +" "+Likes+" " +Hearts);
}
}
}
catch(JSONException e){Log.e(TAG,e.toString());}
try{
JSONObject responseJson = new JSONObject(response);
if(responseJson.has("result")){
JSONArray resultJsonArr = responseJson.getJSONArray("result");
for(int i=0; i<resultJsonArr.length(); i++){
JSONObject resultInstanceJson = resultJsonArr.getJSONObject(i);
if(resultInstanceJson.has("result")){
JSONArray resultArr = resultInstanceJson.getJSONArray("result");
for(int j=0; j<resultArr.length(); j++){
JSONObject jsonResult = resultArr.getJSONObject(j);
String profileNAme = jsonResult.getString("ProfileName");
String imageUrl = "", videoUrl = "";
//image url
if(jsonResult.has("ImageUrl")){
imageUrl = jsonResult.getString("ImageUrl");
}
//video url
if(jsonResult.has("VideoUrl")){
videoUrl = jsonResult.getString("VideoUrl");
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
try this way
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
JSONArray innerResult = jo.getJSONArray("result");
int size = innerResult.legth();
for (int j = 0; j < size; j++) {
JSONObject innerJo = innerResult.getJSONObject(j);
abcd.add(innerJo.getString("ProfileName"));
}
}
Edit:
public class InfoHolder {
public String profileName;
public String imageUrl;
public String videUrl;
}
for (int j = 0; j < size; j++) {
InfoHolder holder = new InfoHolder();
JSONObject innerJo = innerResult.getJSONObject(j);
// the same for imageUrl and videoUrl
holder.profileName = innerJo.getString("ProfileName");
abcd.add(holder);
}
of course you have to change from String to InfoHolder your abcd collectio
Try this:
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j < i; j++) {
JSONObject jo = ja.getJSONObject(j);
JSONArray resultJA = jo.getJSONArray("result");
for(int k=0;k< resultJA.length();k++){
JSONObject jo_inside = resultJA.getJSONObject(k);
String profileName = jo_inside.getString("ProfileName");
//use optString on JSONOBject. it will return empty String if that key does not exists or else the value u want. it won't give any exceptions.
String ImageURL = jo_inside.optString("ImageUrl");
String VideoURL = jo_inside.optString("VideoUrl");
}
}
}
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
You do
for (int i = 0; i < ja.length(); i++) {
ok for the first array now you need to get the array inside each cells of the first
For example :
JSONObject jo = ja.getJSONObject(i);
JSONArray ja2 = jo.getJSONArray("result");
then and only then you do the second loop
Maybe this answer isn't complete but the idea is here