I am new to Stackoverflow and this is my first question.
I am developing an application where I am reading data from a json file from assets folder and storing the values in array list.
here is my code
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(String.valueOf(jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return rootview;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And this is my json data structure
"root" : {
"child" : [ "data1","data2","data3",.......]},
I want the data1,data2 values inside a list
Try this
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
list.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(jsonObject.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Related
I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}
Here is the code i had tried with multiple times to get multiple rows values in a single text view with json.
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("survey_textresponse"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
}
}
}
when i run php file in chrome directly it shows all values from database while in android app it shows only the first row value.
Because you are only storing the last value of JSONobject in json reference
// assume JArray length = 5
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
// only have last object value , in last iteration jArray.getJSONObject(4)
}
There can be many solutions to this
Collect data as list of Values
Collect in a String or StringBuilder Object
StringBuilder sb = new StringBuilder();
// or List<String> list = new ArrayList<>();
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
sb.append(json.optString("survey_textresponse")+"\n");
// or list.add(json.optString("survey_textresponse"));
}
and later
textview.setText(sb.toString());
// or can collect list as string using loop and display it
The loop that you've written for retrieving the values from the JSONArray is not proper. Its only storing the last object while iterating through the loop. You could store the retrieved values in a collection of string.
Here's an example code you could follow:
private class RetrieveTask extends AsyncTask<Void,Void,Void>{
List<String> jsonResults;
String str;
JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonResults=new ArrayList<>();
}
#Override
protected void onPostExecute(Void aVoid) {
for(String data:jsonResults)
textview.append(data);
}
#Override
protected Void doInBackground(Void... voids) {
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
if(json.optString("survey_textresponse")!=null){
jsonResults.add(json.getString("survey_textresponse"));
}
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your json variable contains only last element of JsonArray when it is finished. You can display on TextView while retrieving your values from JsonArray.
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
textview.setText(textview.getText() + json.getString("survey_textresponse") + "\n");
}
I have JSON file in assets and I'm trying to read it in my MainActivity method:
private static List<JSONObject> getJSONArray(Context context) {
JSONArray myJSONarr=new JSONArray();
try
{
AssetManager am = context.getAssets();
InputStream is = am.open("chineesecardsdata.json");
String resultJson = is.toString();
is.close();
Log.d("mainActLog","file read ok: "+resultJson);
try {
}
catch (JSONException e)
{
}
}
catch(
IOException e)
{
Log.d("mainActLog","file read fail");
}
}
In log I have:
file read ok:
android.content.res.AssetManager$AssetInputStream#b123fb4
public String loadJSONFromAsset( Context context ) {
String json = null;
try {
InputStream is = context.getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
parse JSON
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray array = new JSONArray(loadJSONFromAsset());
}
} catch (JSONException e) {
e.printStackTrace();
}
How to access volley response {"data":"success"} like this.
i am already try this
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
You're trying to access a JSONArray from a JSONObject while it's just a string. So just replace getJSONArray with getString and try this
String data = new JSONObject(response).getString("data");
Or in your code
try {
JSONObject j = new JSONObject(response);
result = j.getString("data");
}
catch (JSONException e) {
e.printStackTrace();
}
Access Like This
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getString("data");
} catch (JSONException e) {
e.printStackTrace();
}
You can check this, before retrieving check if that tag (i.e. "data" for your case) is exists on that json object.
JSONObject j = null;
try {
j = new JSONObject(response);
if(j.has("data") {
result = j.getString("data");
}
} catch (JSONException e) {
e.printStackTrace();
}
As the value of data is string and to get string value you have to use JSONObject.getString("data")
Use:
result = j.getString("data");
Instead of:
result = j.getJSONArray("data");
I kept some JSON data in a txt file inside assests folder. Then i am reading the txt file and kept the result in a string. Now i am trying to convert the string to JSONObject and get some data from each key. Below is the code.
========method for reading from a file:
private String readMyJsonFile()
{
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("myFile.txt"), "UTF-8"));
mLine = reader.readLine();
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return mLine;
}
======= And inside onCreate():
String JsonStr = readMyJsonFile();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = JsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext())
{
String currentDynamicKey = (String)keys.next();
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
}
}
catch (JSONException e) {e.printStackTrace(); }
================================================
and the JSON data is:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
}
==========================================================
I am getting result but the problem is that i am not getting the JSONObject serially in JSONObject jsonObj = new JSONObject(JsonStr); . The sequence is not the same as the JsonStr.
How to solve it?
Take the iterator keys in a ArrayList of string. Then loop through each arraylist object and get the JsonObjects. Following is the code that might help:
String JsonStr = readMyJsonFile(); //readMyJsonFile() is the same method you created
ArrayList<String> sortedKey = new ArrayList<String>();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = jsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
sortedKey.add(currentDynamicKey);
}
Collections.sort(sortedKey);
for(String str:sortedKey )
{ JSONObject currentDynamicValue = questionMark.getJSONObject(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
It is not JSON:
"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
It is JSON:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}}
and it JSON:
{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}