array of objects - android

For post method in android
I have to send array of objects.
I am retrieving elements from an arrayList and putting that retrieved element in JSONObject and than putting that in JSONobject in JSONArray.
JSONArray ccArray = new JSONArray();
{
JSONObject object = new JSONObject();
if (ccArrayList.size() != 0) {
for (int i = 0; i < ccArrayList.size(); i++) {
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
}
} else {
object.put("", "");
}
}
When there are more than 2 or more than 2 elements in arraylist it is adding the last element in ccrray as many times as their are elements in the list.
output :
"cc":[{"emailId":"f#j.com"},{"emailId":"f#j.com"}]

Change code like this
JSONObject obj = new JSONObject();
JSONArray ccArray = new JSONArray();
for (int i = 0; i < ccArrayList.size(); i++) {
JSONObject object = new JSONObject();
if (ccArrayList.size() != 0) {
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
} else {
object.put("", "");
}
}
obj.put("cc",ccArray);

Code:-
ArrayList<String> ccArrayList = new ArrayList<String>();
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
JSONArray ccArray = new JSONArray();
if(ccArrayList.size()>0){
for(int i=0;i<ccArrayList.size();i++){
JSONObject object = new JSONObject();
try {
object.put("emailId", ccArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
ccArray.put(object);
}
}
Output:-
ccArray: [{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"}]

That's because you declared JSONObject object = new JSONObject(); outside the for loop, so each time it loops the object adds a new JSONObject and also does the array. Try keeping it within the loop:
JSONArray ccArray = new JSONArray();
for (int i = 0; i < ccArrayList.size(); i++) {
JSONObject object = new JSONObject();
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
}

Related

how to post nested Json Array to server?

Hi i want to post this a json array which has two json arrays of Integers in them to server using JsonObject
"job_experiences": [
{
"job_category": [Integer],
"experience_level": [Integer]
}
]
JsonArray list = new JsonArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list.add(selectedJobs.get(i));
}
JsonArray list2 = new JsonArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list2.add(selectedJobs.get(i));
}
JsonObject postData = new JsonObject();
postData.add("job_category", list);
postData.add("experience_level", list2);
Please use JSONObject instead of JsonObject and JSONArray instead of JsonArray,
Try below approach and check
JSONArray list = new JSONArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list.put(selectedJobs.get(i));
}
JSONArray list2 = new JSONArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list2.put(selectedJobs.get(i));
}
JSONObject postData = new JSONObject();
try {
postData.put("job_category", list);
postData.put("experience_level", list2);
JSONArray job_experiences = new JSONArray();
job_experiences.put(postData);
JSONObject jsonObject_job_experiences = new JSONObject();
jsonObject_job_experiences.put("job_experiences", job_experiences);
Log.e("jsonObject_job_exp", jsonObject_job_experiences.toString());
} catch (JSONException e) {
e.printStackTrace();
}
and in the log you can see the final JSONObject

how can I collect the array heroes in my android studio project below

my function is
public String[] loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[3];
for (int i = 0; i < 3; i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
// heroes[i] = obj.getString("name");
heroes[i]= "https://static.pexels.com/photos/1543/landscape-nature-man-person-medium.jpg";
}
return heroes;
}
this is where i called it but it is returning null array for me
String s="";
try {
items= loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
The line JSONArray jsonArray = new JSONArray(json); may be crashing due to json not being a valid json array. This would cause the array to be null, as it hasn't been initialized yet.
Your exception handler out of for. If you catch exceptions in for body, you can parse verified json items. If a item not correct, you can pass.
For example,
public String[] loadIntoListView(String json) {
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> heroes = new ArrayList();
for (int i = 0; i < jsonArray.length; i++)
{
try{
JSONObject obj = jsonArray.getJSONObject(i);
heroes.add(obj.getString("name"));
}catch(JSONException ignore_errors){
}
}
return heroes.toArray(new String[0]);;
}

Parse list inside a json in android

I am putting a list in the json and now I want to get the list and display each entry in different textview. This is my code to put the list in json and to get the same
static ArrayList<String> list = new ArrayList<String>();
JSONObject json = jsonFruitArray.getJSONObject(i);
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku",new JSONArray(list));
This is how i am trying to get the list
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
You should try like this. Use JsonArray
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("1", 1);
jsonObject.put("2", 2);
jsonObject.put("3", 3);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray result = new JSONArray();
result.put(jsonObject);
//Use json array
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("John");
jsonArray.put("Mat");
jsonArray.put("Jason");
jsonObj.put("json_array", jsonArray);
//Retrieve like this
JSONArray jsonFruitSkuArray = jsonObj.getJSONArray("json_array");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
In your code you can try following :
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject();
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku", new JSONArray(list));
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for (int iSku = 0; iSku < jsonFruitSkuArray.length(); iSku++) {
String element = jsonFruitSkuArray.getString(iSku);
System.out.println(element);
}

Convert JSONArray into a String Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Probably a stupid question. I'm getting a JSONArray in the form of
[{'route':'route1'}, {'route':'route2'}, {'route':'route3'}]
I want to get it into a String array of
["route1", "route2", "route3"]
How?
The solution that comes to my mind would be to iterate through and just grab the values
String[] stringArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringArray[i]= jsonArray.getJSONObject(i).getString("route");
}
Try this
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(responseString);
if (jsonArray != null) {
String[] strArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
strArray[i] = jsonArray.getJSONObject(i).getString("route");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Followed by this TUTORIAL
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(i = 0; i < arr.length; i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Or use GSON
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
//(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
//(Deserialization)
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
//ints2 is same as ints
You can try below solutions,
Just replace { and } by following code
String jsonString = jsonArray.toString();
jsonString.replace("},{", " ,");
String[]array = jsonString.split(" ");
Or
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(i = 0; i < arr.length; i++){
list.add(arr.getJSONObject(i).getString("name"));
}
this will convert to Arraylist and then if you want it to string then convert it to StringArray. for more reference use this link
as straight forward as it can be
List<String> list = new ArrayList<String>();
for( int ix = 0; ix < yourArray.length(); ix++ ){
list.add( yourArray.getJSONObject( ix ).getString( "route" ) );
}
return list.toArray( new String[] );
// try this way here i gave with demo code
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("route","route1");
jsonArray.put(jsonObject1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("route","route2");
jsonArray.put(jsonObject2);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("route","route3");
jsonArray.put(jsonObject3);
String[] array = jsonArrayToArray(jsonArray);
for (int i=0;i<array.length;i++){
Log.i((i+1)+" Route : ",array[i]);
}
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public String jsonToStrings(JSONObject object) throws JSONException {
String data ="";
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
data+=fromJson(object.get(key)).toString()+",";
}
return data;
}
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToStrings((JSONObject) json);
} else if (json instanceof JSONArray) {
return jsonArrayToArray((JSONArray) json);
} else {
return json;
}
}
private String[] jsonArrayToArray(JSONArray array) throws JSONException {
ArrayList<Object> list = new ArrayList<Object>();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
ArrayList<String> arrayList = new ArrayList<String>();
for (int i=0;i<list.size();i++){
String[] row = ((String)((String)list.get(i)).subSequence(0,((String)list.get(i)).length()-1)).split(",");
for (int j=0;j<row.length;j++){
arrayList.add(row[j]);
}
}
String[] strings = new String[arrayList.size()];
for (int k=0;k<strings.length;k++){
strings[k]=arrayList.get(k);
}
return strings;
}
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources