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();
}
Related
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();
}
I have an ArrayList that contains values as follows
"One"
"Two"
"Three" etc.
I am trying to generate an JSON Object / Array out of this. My code is below:
peopleNames = personAdapter.getArrayListNames();
peoplePhones= personAdapter.getArrayListPhones();
JSONNames = new JSONObject();
JSONPhones = new JSONObject();
for (int i = 0; i < peopleNames.size(); i++){
try {
System.out.println(peopleNames.get(i));
JSONNames.put("Name",peopleNames.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < peoplePhones.size(); i++){
try {
JSONPhones.put("Phone",peoplePhones.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
jsonArrayNames = new JSONArray();
System.out.println(jsonArrayNames.toString());
However my output is just:
[{"Name":"One"}]
Why don't you merge the data ? I think, from your adapter, you're able to get people directly, right ? If so, I propose you the following :
people = personAdapter.getPersons();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < people.size(); i++) {
JSONObject object = new JSONObject();
object.put("Name", people.name());
object.put("Phone", people.phone());
jsonArray.put(object);
}
The resulted JSON will be :
[
{"Name":"One",
"Phone": "OnePhone"},
{"Name":"Two",
"Phone": "TwoPhone"},
]
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.
I have a JSON response which look something like this( its different from user to user)
{
"success": true, "data":
[
{
"mandatory_tag": "My Company",
"id": "topic_1408946825893148"
},
{
"mandatory_tag": "Partners",
"id": "topic_1408946942491149",
},
{
"mandatory_tag": "Industry",
"id": "topic_1408946996510150",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210454810358",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947133657152"
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947071457151",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210621754362",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210704390363",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210794791364"
}
]
}
I am parsing it and trying to store in HashMap, but the key value is duplicating. Can anyone suggest me how can i store all id with same mandatory_tag in one array?
I am new to this so please consider..thanks
try
{
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
} else
{
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
And well i got stuck at this now..any good logic please..
A hashmap allows you to store key-value items. I would suggest the HashMap be of type <String,List<String>> so allowing you to store items with the same mandatory_tag in the same list under 1 key.
For example
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
if (myMap.containsKey(mandatory_tag)) {
List<String> values = myMap.get(mandatory_tag);
if (values!=null) {
values.add(id)
} else {
values = new List<String>();
values.add(id);
}
}
Update
As I wrote in my comment below, the except you added has an error
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
What you are doing here is, if the map already contains the key you are replacing the value associated with the key with a new list which contains only 1 value. What you need to do is update the list of already existing values. Check the code below and make sure you understand the problem. These are fundamentals of programming and you need to understand the logic of what you're doing to advance.
//Somewhere you have declared your HashMap
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
//then we continue with your excerpt
try {
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++) {
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.containsKey(mandatory_tag)) {
List<String> arrayID = myMap.get(mandatory_tag);
arrayID.add(id);
} else {
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
Create a POJO called TagValues(or whatver name you would like) with variables mandatory_tag,id and then and create an ArrayList<TagValues> in which you can store all the objects.
Thanks for your response, but with help of you guys, i got the solution
`HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.isEmpty())
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
}`
In those cases, I'd like to use a custom HashMap:
public MMap getData() {
MMap result = new MMap();
JSONArray array = getJSONArrayFromTotalJSON();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String mtag = obj.getString(MANDATORY_TAG);
String id = obj.getString(ID);
result.put(mtag, id);
}
return result;
}
public class MMap extends HashMap<String, List<String>> {
public void put(String key, String value) {
if (!this.containsKey(key))
this.put(key, new ArrayList<String>());
this.get(key).add(value);
}
}
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();
}
}