Retrieved item iterated instead adding new value - java

I'm retrieving data from JSON like below :
worker: [{
content: "android"
}, {
content: "java"
}]
So I supposed that I will see values (android, java) but it doesn't happen i only see java iterated :
And this my way to get this length of array I retrieved from JSON:
I get the array correctly and pass it with SharedPreference :
JSONArray workerArr = object.getJSONArray("worker");
String jsonString = workerArr.toString();
SharedPreferences settings = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("jsonString", jsonString);
editor.commit();
Then I get this length by this way simply :
SharedPreferences settings = getSharedPreferences("pref", 0);
String jsonString = settings.getString("jsonString", null);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.i(TAG, "displayCommentsJsonArray: " + jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
And here is how i add retrieved item to list...
List<String> top250 = new ArrayList<String>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
String value = "";
value = mCursor.getString(ArticleLoader.Query.WORKERS);
top250.add(value);
listDataChild.put(listDataHeader.get(0), top250);
}
}
So i should see two values in my list instead of same values with same count of array..
i don't know what i missed?
my mCursor throw this value in log :
prepareListData: java prepareListData: java

You are iterating the jsonArray, but I can't see any code where you parse the data from it.
Move the listDataChild.put(listDataHeader.get(0), top250); outside the loop. (As #Sac pointed)
Try the code below.
if (jsonArray != null) {
List<String> top250 = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String value = object.getString("content");
top250.add(value);
}
listDataChild.put(listDataHeader.get(0), top250);
}
I don't know the content of mCursor variable.

Related

JSONObject getString returns null on first run

I have this String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
which is on array list, I want to put them on the variable on each loop and save it to the database, but for now I do this code for debugging purpose because at the first loop of the code it is suuposed to output "qty" value but instead it is a null like this {"pname":"7","qty":"222"} null but on the next run of loop it outputs this {"pname":"8","qty":"5"} 222 it seems that on the second loop the first objects qty value is then taken on the second loop, the final output is this
{"pname":"7","qty":"222"} null {"pname":"8","qty":"5"} 222 {"pname":"10","qty":"65"} 5
and this is the code that I have
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(txtQty).append(" ");
}
}
can anyone help me about this? any help will be so much appreciated, Thanks!!!
You are assigning wrong value to txtQty rather than the current value in the JSONObject:
HashMap Put Method (From Docs):
Returns:
the previous value associated with key, or null if there was no
mapping for key. (A null return can also indicate that the map
previously associated null with key.)
Thats why you are getting null at first attempt and 222 at second.
Following code will give you desired result:
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(jsonObject.getString("qty")).append(" ");
}
}

Get JSON Array into strings.

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();
}
}

Java how to remove strings from JSONArray

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]

Initializing array for JSON data advice

I am trying to store data gotton from JSON to an normal string array. The problem is i cant seem to initialize the array size according to the number for JSON data.
For now i declare the array size my own:
String[] path= new String[5];
This is the JSON part:
class Loadpath extends AsyncTask {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_imageDB, "GET",params);
try {
JSONArray productObj = json.getJSONArray(TAG_IMAGEDB); // JSON Array
// looping through All path
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
path[i] = image.getString(TAG_PATH);
}
} else {
displayPath.setText("No path");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
So my goal is the array size is gotten from the JSON.length().. Any idea how I can achieve this?
initialize the mStrings[ ] array size according to the JSONArray length as:
String[] mStrings; //<< Declare array as
mStrings = new String[productObj.length()]; //<<initialize here
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings[i] = image.getString(TAG_PATH);
}
and it is good if you use ArrayList instead of String Array as for getting values from Jsonobject as:
ArrayList<String> mStrings=new ArrayList<String>(;
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings.add(image.getString(TAG_PATH));
}
Maybe u can use List instead of String array

Convert Json Array to normal Java list

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())

Categories

Resources