JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
lets say we have this jsonArray, there are strings empty, how to remove them without leaving gaps?
You can use the following code :
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String val = jsonArray.getJSONObject(i).getString();
if (val.equals("empty")) {
jsonArray.remove(i);
}
}
take a look at this post.
Make a list to put the indexes of the elements with the "empty" string and iterate over your list (the one with the "empty" elements) saving the indexes of the items to delete. After that, iterate over the previosly saved indexes and use
list.remove(position);
where position takes the value of every item to delente (within the list of index).
Should work with few fixes to Keerthi's code:
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.get(i).equals("empty")) {
jsonArray.remove(i);
}
}
You can use this following code
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item string equal to "empty"
if (!"empty".equals(jsonArray.getString(i))
{
list.put(jsonArray.get(i));
}
}
//Now, list JSONArray has no empty string values
}
you can use string replace after converting the array to string as,
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
System.err.println(jsonArray);
String jsonString = jsonArray.toString();
String replacedString = jsonString.replaceAll("\"empty\",", "").replaceAll("\"empty\"", "");
jsonArray = new JSONArray(replacedString);
System.out.println(jsonArray);
Before replace:
jsonArray is [1,"empty",2,3,"empty",4,"empty"]
After replace:
jsonArray is [1,2,3,4]
Related
I am running a loop where I am getting JSON Objects as inputs how do I append all these JSONObjects in a JSONArray?
The input is a JSONObject which contains a string based key value pair called "name" which I want to extract.
Following is what I tried, I am not able to append all of them together using the following code rather they are appearing one at a time.
List<String> hoi2 = new ArrayList();
if(input != null) {
hoi2.add(input.getString("name"));
}
System.out.println(hoi2);
Sample input format (Getting One Input at a time):
{"lon":77.5858225,"name":"bingo","lat":12.9171587}
{"lon":77.5858225,"name":"dingo","lat":12.9171587}
{"lon":77.5858225,"name":"lingo","lat":12.9171587}
Required result:
["bingo","dingo","lingo"]
My current result:
["bingo"]
["dingo"]
["lingo"]
Update:
I realised the issue my approach was wrong since my array was going blank after every input and re-writing it hence had to define a global variable.
For below code:
List<Integer> hoi2 = new ArrayList<Integer>();
for(int i=0; i<3; i++){
hoi2.add(i);
}
System.out.println(hoi2);
Output will be:
[0, 1, 2]
For below code:
for(int i=0; i<3; i++){
List<Integer> hoi2 = new ArrayList();
hoi2.add(i);
System.out.println(hoi2);
}
Output will be:
[0]
[1]
[2]
JSONArray jArray = new JSONArray();
for (int i = 0; i < docList.size(); i++) {
JSONObject json = new JSONObject(hoi2.get(i));
jArray.put(json);
}
here may post complete solution please refer it.
Code :
List<String> hoi2 = new ArrayList();
hoi2.add("{\"lon\":77.5858225,\"name\":\"bingo\",\"lat\":12.9171587}");
hoi2.add("{\"lon\":77.5858225,\"name\":\"dingo\",\"lat\":12.9171587}");
hoi2.add("{\"lon\":77.5858225,\"name\":\"lingo\",\"lat\":12.9171587}");
JSONArray jsonArray = new JSONArray();
try {
for (int i = 0; i < hoi2.size(); i++) {
JSONObject jsonObject = new JSONObject(hoi2.get(i));
System.out.print(jsonObject.getString("name"));
jsonArray.put(jsonObject.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(jsonArray.toString());
output :
["bingo","dingo","lingo"]
from the following link , I need to get the value stored in "media".
Here is my code:
Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
But I can not access past "items"
You will have to loop through the JSON like this:
...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
String media = jsonMainNode.getJSONObject(i).getString("media");
}
This will loop through the images and return the value(s) in media.
In your case it should be something like this:
..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
JSONObject finalNode = jsonMainNode.getJSONObject(i);
JSONArray finalArray = finalNode.optJSONArray("media");
for (int j=0; j<finalArray.length(); j++) {
String m = finalArray.getJSONObject(j).getString("m");
}
}
...because there is another node inside the media node, called m.
Here is an example getting the tags string for each item in the JSONArray that you have:
for (int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonObject = jsonMainNode.getJSONObject(i);
String tags = jsonObject.getString("tags");
}
This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject item = (JSONObject) jsonMainNode.get(i);
JSONObject media = item.getJSONObject("media");
String valueMedia = media.getString("m");
Log.d("TAG", valueMedia);
}
I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm prsing information from a json file and showing data in a custom ListView. Now, I have an Array named authors. Where authors are multiple. But, in ListView I can only see the last authors name or last array item .
How can I show all items ? Here is my code
for (int index = 0; index < jsonArray.length(); index++)
{
HashMap<String, String> temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);
temp.put(KEY_AUTHOR, authordName);
That's probably why. You are iterating over the all authors but HashMap will override values and only the last one is being saveed.
As I understand you are getting back a JSON response with an array of JSONObject. Each JSONObject holding some info and a sub-JSONArray of associated authors.
The easiest approach could be just building ArrayList<JSONObject> and extending BaseAdapter implementing an adapter of your own. It's very easy. For large collections of data search on ViewHolder pattern, for optimization.
'HashMap<String, String> temp;
for (int index = 0; index < jsonArray.length(); index++)
{
temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);'
you declare the "HashMap"line in above the onstart values.it will help for you.
Is there a way to convert JSON Array to normal Java Array for android ListView data binding?
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
If you don't already have a JSONArray object, call
JSONArray jsonArray = new JSONArray(jsonArrayString);
Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
Instead of using bundled-in org.json library, try using Jackson or GSON, where this is a one-liner. With Jackson, f.ex:
List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
Maybe it's only a workaround (not very efficient) but you could do something like this:
String[] resultingArray = yourJSONarray.join(",").split(",");
Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)
Using Java Streams you can just use an IntStream mapping the objects:
JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
.mapToObj(array::get)
.map(Object::toString)
.collect(Collectors.toList());
Use can use a String[] instead of an ArrayList<String>:
It will reduce the memory overhead that an ArrayList has
Hope it helps!
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
parametersArray[i] = parametersJSONArray.getString(i);
}
I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
for (Long s : list) {
System.out.println(s);
}
}
Works also with array of strings
Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();
...
we starting from conversion [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
example :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
You can use a String[] instead of an ArrayList<String>:
Hope it helps!
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
We can simply convert the JSON into readable string, and split it using "split" method of String class.
String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");
To improve Pentium10s Post:
I just put the elements of the JSON array into the list with a foreach loop. This way the code is more clear.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
jsonArray.forEach(element -> list.add(element.toString());
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
You can use iterator:
JSONArray exportList = (JSONArray)response.get("exports");
Iterator i = exportList.iterator();
while (i.hasNext()) {
JSONObject export = (JSONObject) i.next();
String name = (String)export.get("name");
}
I know that the question was for Java. But I want to share a possible solution for Kotlin because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray() directly on a JSONArray instance.
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())