I am trying to add all the JSONobject arrivals in the for loop JSONobject stops outside but I am always just getting one JSONObject in the stops. How can I put all the arrivales JSONObject in the for loop in the JSONObject stops?
I am using the json library org.json.
I appreciate any help
JSONObject stops = new JSONObject();
for (Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
stops.put("stops_name", key);
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
JSONArray timeArray = new JSONArray(timeEntries);
arrivalMoFr.put( timeArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
}
Declare the object outside loop and keep adding items in loop. Your arrivals and arrivalMoFr are instantiated every time loop runs and you gets the last ites. Try this
JSONObject stops = new JSONObject();
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
stops.put("stops_name", key);
JSONArray timeArray = new JSONArray(timeEntries);
arrivalMoFr.put( timeArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
System.out.println(stops.toString(3));
} 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 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 arraylist that needs to be converted to json array to post in the server
the format of json should be like this:
{
p:1,
s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4]
}
Let say I have:
List<MyObject> objectList = new ArrayList<MyObject>();
MyObject myObject = new MyObject();
myObject .setA(1);
myObject .setB(2);
myObject .setA(2);
myObject .setB(3);
myObject .setA(3);
myObject .setB(4);
objectList.add(myObject);
My current code is:
for (int i = 0; i < objectList.size(); i++) {
JSONArray ar = new JSONArray();
ar.put("a:"+objectList.get(i).getA());
ar.put("b:"+objectList.get(i).getB());
jOuter.put("s",ar);
}
but this doesnt work, the current return is:
{"p":1,"s":["a:20","b:10.0"]}
Thanks.
Shouldn't it be something like this?
JSONArray ar = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject objects = new JSONObject();
objects.put("a", objectlist.get(i).getA();
objects.put("b", objectlist.get(i).getB();
ar.put(objects);
}
jOuter.put("s",ar);
Your s entry is actually a JsonArray, while your p is just a property. Here I am using Gson but you could easily apply it to whichever library you are using. So you can do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("p", 1);
JsonArray sArr = new JsonArray();
for (int i = 0; i < objectList.size(); i++)
{
JsonObject innerObj = new JsonObject();
innerObj.addProperty("a:"+objectList.get(i).getA());
innerObj.addProperty("b:"+objectList.get(i).getB());
sArr.add(innerObj);
}
jObj.addProperty("s", sArr);
The output is:
{
"p":1,
"s":[{"a":1,"b":2},{"a":3,"b":4}]
}
Your required format is invalid.
I think you are looking for something like this
{
"p": 1,
"s": [
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 3
},
{
"a": 3,
"b": 4
}
]
}
For this code will be like as below
JSONArray jArray = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject job= new JSONObject();
job.put("a",objectList.get(i).getA());
job.put("b",objectList.get(i).getB());
jArray .put(job);
}
try {
jOuter.put("s", jArray );
} catch (JSONException e) {
e.printStackTrace();
}
Please check following code: This will make the proper formatting:
JSONObject jo = new JSONObject();
try {
jo.put("p", "1");
JSONArray jarr = new JSONArray();
for (MyObject listItem : objectList) {
JSONObject inner = new JSONObject();
inner.put("a", listItem.getA());
inner.put("b", listItem.getB());
jarr.put(inner);
}
jo.put("s", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return output like:
{
"p":1,
"s":[{"a":1,"b":2},{"a":2,"b":3},{"a":3,"b":4}]
}
This makes a proper json, which I think you need! Do let me know, if I am wrong somewhere.
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();
}
}
How can I convert this string into JSONArray ?
{"result":{"passion":[{"id":2,"description":"Sushi"},{"id":3,"description":"Dinner"},{"id":4,"description":"Sex"},{"id":5,"description":"Boobies"},{"id":6,"description":"Sleep"},{"id":7,"description":"Cars"},{"id":8,"description":"Travel"},{"id":9,"description":"Soccer"},{"id":10,"description":"Silice"}]}}
I'm trying to do:
JSONArray jsonArray = jsonObject.getJSONArray("passion");
But I am getting an exception:
org.json.JSONException: No value for passion
is seems like you are not getting result object
JSONArray jsonArray = jsonObject. getJSONObject("result").getJSONArray("passion");
may be this is what you need dear
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();
}
}
Use this code
JSONObject jsonObject = new JSONObject(json);
JSONObject resultValues = jsonObject.getJSONObject("result");
JSONArray passionArray = resultValues.getJSONArray("passion")