Android convert JSONArray to String Array - java

I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
if (jsonStr != null) {
try {
foodsFilter = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foodsFilter.length(); i++) {
JSONObject c = foodsFilter.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String filter_type = c.getString(TAG_FILTER_TYPE);
//String item_list = c.getString(TAG_ITEM_LIST);
JSONArray itemList = new JSONArray(c.getString("item_list"));
String item_list = itemList.toString();
// tmp hashmap for single contact
HashMap<String, String> filter = new HashMap<String, String>();
// adding each child node to HashMap key => value
filter.put(TAG_CATEGORY_NAME, category_name);
filter.put(TAG_FILTER_TYPE, filter_type);
filter.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodsFilterList.add(filter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]
I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}
So I can send it into another activity use Intent and show it in ListView

What you have
String item_list = itemList.toString();
You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}
Now you can add the strings to a list/array and then do what is required.

Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}

Related

Parse json in Java android studio

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

Call single object from Json file

I am learning how to implement Json in my project and have this Json file:
{
"stations":[
{
"station":"no1",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
}
]
}
I am able to succesfully display all values in a TextView, but I am only interested in lets say station no1. How do I pass the values from only station no1 in a textView?
This is my Json code:
try {
JSONObject jsonObject = new JSONObject(contents);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
} catch (JSONException e) {
e.printStackTrace();
}
Instead of using
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
You can do
JSONObject stations = jsonArray.getJSONObject(0);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
This way you will only get the values of the first element in your JSON.
Intead of using loop to all array length, get only first object details like below :
try {
JSONObject jsonObject = new JSONObject(contents);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
JSONObject stations = jsonArray.getJSONObject(0);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
} catch (JSONException e) {
e.printStackTrace();
}

How do I properly parse this JSON?

I have a big JSON file that contains Countries, States and Cities. The JSON looks like this:
{
"Countries":[
{
"CountryName":"India",
"States":[
{
"StateName":"Maharashtra",
"Cities":[
"Pune",
"Nagpur",
"Mumbai"
]
},
{
"StateName":"Kerala",
"Cities":[
"Kochi",
"Munnar"
]
}
]
},
{
"CountryName":"Australia",
"States":[
{
"StateName":"Aukland",
"Cities":[
"GlenField",
"Henderson",
"MilFord"
]
},
{
"StateName":"Melbourne",
"Cities":[
"Melbourne",
"South Oakleigh"
]
}
]
}
]
}
I have an activity in my app that requires the user to select a country and upon selecting a country I want to get all the states of that country as an array list. And when a specific state is selected, I want to get all the cities of that state as an array list.
I am able to get a list of all Countries using this method:
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString(child));
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Contries.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;
}
Then, in the onCreate method, using this line gives me all the countries in an array list
loadCountries("Countries", "CountryName", countries);
Since this is my first time working with a JSON file in AndroidStudio/Java, I have no idea what to do to get the states and the cities. Any help is greatly appreciated.
You could use GSON library. Just create corresponding java object which will reflect json structure and do like here:
MyClass data = new Gson().fromJson(json, MyClass.class);
Respect for trying to do this yourself, but we live in the age of the API. Check out Google's GSON library, it parses JSON to java objects, and java objects to JSON. It's one of the most useful APIs out there. https://github.com/google/gson
Try this:
Map<String, Map<String, Map<Integer, String>>> data = new HashMap<>();
try {
JSONObject object = new JSONObject(loadJSONFromAsset());
JSONArray countries = object.getJSONArray("Countries");
for (int i = 0; i < countries.length(); i++) {
JSONObject state = countries.getJSONObject(i);
JSONArray statesList = state.getJSONArray("States");
String countryName = countries.getJSONObject(i).getString("CountryName");
for (int j = 0; j < statesList.length(); j++) {
JSONObject city = statesList.getJSONObject(j);
JSONArray citiesList = city.getJSONArray("Cities");
String stateName = city.getString("StateName");
Map<String, Map<Integer, String>> stateHashMap = new HashMap<>();
for (int k = 0; k < citiesList.length(); k++) {
cityList.add(citiesList.getString(k));
String cityName = citiesList.getString(k);
Map<Integer, String> cityHashmap = new HashMap<>();
cityHashmap.put(k, cityName);
stateHashMap.put(stateName, cityHashmap);
data.put(countryName, stateHashMap);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Not able to retrieve hashmap from sharedPreferences

I am retrieving list of ParseObject from Parse and casting into list of HashMap,then converting it to JSONArray and storing in SharedPrefrences as String
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < list.size(); i++) {
ParseObject foundObject = list.get(i);
HashMap<String, Object> industry = new HashMap<String, Object>();
industry.put("CategoryName", foundObject.get("category"));
industry.put("lastUpdated", new Date());
industry.put("Jobs", foundObject.getList("jobs"));
data.add(industry);
}
JSONArray result = new JSONArray(data);
editor.putString("Categories", result.toString());
editor.commit();
Then i am retrieving from locally saved String(JSONArray)
String storedCollection = pref.getString("Categories", null);
//Parse the string to populate your collection.
collection = new ArrayList<HashMap<String, Object>>();
if (storedCollection != null) {
try {
JSONArray array = new JSONArray(storedCollection);
HashMap<String, Object> item = null;
for (int i = 0; i < array.length(); i++) {
try {
JSONObject obj = new JSONObject((String) array.get(i));
Iterator<String> it = obj.keys();
item = new HashMap<String, Object>();
while (it.hasNext()) {
String key = it.next();
item.put(key, obj.get(key));
}
if (item == null) {
JSONObject obj2 = (JSONObject) array.get(i);
Iterator<String> it1 = obj2.keys();
item = new HashMap<String, Object>();
while (it1.hasNext()) {
String key = it.next();
item.put(key, obj2.get(key));
}
}
} catch (JSONException e) {
}
collection.add(item);
}
} catch (JSONException e) {
Log.e("JSON", "while parsing", e);
}
}
Which works fine on and above lollipop version but giving error on lower versions
org.json.JSONException: Unterminated array at character 21 of
{jobs=[Bar management, Baker, Bar service, Barista, Car park services,
Chef, Cleaning services, Cooking & food preparation], lastUpdated=Tue
Jun 28 10:22:03 GMT+05:30 2016, category=fulltime}
and sometimes getting this error
java.lang.ClassCastException: org.json.JSONObject cannot be cast to
java.lang.String
The problem is the array that you store is JSONArray of HashMaps. When you retrieve the array, the objects in the array are strings(representing HashMap). JSONObject obj = new JSONObject((String) array.get(i)); which you are trying to convert to JSONObject.This is the problem. Either you convert each of this string back to hashmap or you can use JSONObject in place of HashMap like this to store the data
public void storeInPrefs(){
JSONArray data = new JSONArray();
for (int i = 0; i < list.size(); i++) {
JSONObject industry = new JSONObject();
ParseObject foundObject = list.get(i);
try {
industry.put("CategoryName", foundObject.get("category"));
industry.put("lastUpdated", new Date());
industry.put("Jobs", foundObject.getList("jobs"));
data.put(industry);
}
catch (JSONException e) {
e.printStackTrace();
}
}
SharedPreferences preferences = this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Categories", data.toString());
editor.commit();
}
And to parse the stored data and put it in collection, you can do this
public void parseStoredData(){
SharedPreferences pref = this.getPreferences(MODE_PRIVATE);
String storedCollection = pref.getString("Categories", null);
//Parse the string to populate your collection.
ArrayList<HashMap<String, Object>> collection = new ArrayList<HashMap<String, Object>>();
if (storedCollection != null) {
try {
JSONArray array = new JSONArray(storedCollection);
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
HashMap<String,Object> item = new HashMap<String, Object>();
Iterator<String> it = object.keys();
while (it.hasNext()) {
String key = it.next();
item.put(key, object.get(key));
}
collection.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
Log.e("JSON", "while parsing", e);
}
}
}
In my opinion this would be easy for you.
try to use JSONObject object = new JSONObject(industry);
instead of JSONArray result = new JSONArray(data);
Thie object.toString() is like {"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}
And the result.toString() is like [{"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}]
I think the object is what you really want, and use JsonObject also when retrieving.
Hope helpful.
Addtionally, you can use this to verify your result.

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

Categories