Creating Json Array From Arraylist Android
Solution 1:
You can solve this a bunch of ways. If you want to keep the formatting the way it is you just need to process your strings first. When you get values from your ArrayList
just split the combo into parts
intsplitPoint= combo.indexOf(":")
Stringkey= combo.substring(0, splitPoint);
Stringvalue= combo.substring(splitPoint + 1);
Once you split the key and value out just create a new JSONObject
and add the key and value as a string
JSONObject jObject = newJSONObject();
jObject.put(key, value);
This will add the JSONString to its own JSONObject. Then you can add this object to the JSONArray that you want to create
JSONArray jArray = newJSONArray();
jArray.puJSONObject(jObject);
I broke this down in to parts but if you just decalre your JSONArray
ouside a for loop or some other iterator and loop through your ArrayList
, processing each combo string and adding the resulting object to a JSONArray
you can acheive the desired result
Solution 2:
I am not sure that you can do the following in JSON
[ "key":"value, ...."].
You may be able to do it with Key Value object pairs, as in
[ {"key":"value"},...]
If you do it with objects, you will have to create a new object for each pair, and it might become pretty complicated since the key in JSON corresponds with the name of an instance variable.
My suggestion is to leave it the way you have it now and split the strings. I am not familiar with PHP, but it should be as simple as looping through the JSON array and calling something like split(':') on the strings.
Solution 3:
You can make a JSONObject with dynamic keys like so:
{
"Store #" : "00608",
"Phone #" : "null",
"Address" : "3014 N. SCOTTSDALE RD.",
"City" : "SCOTTSDALE",
"Zip" : "85251",
"State" : "AZ",
"Height" : "6`4",
"Weight" : "230",
....
}
The question what is simpler, can only be answered by you yourself, as obviously you implement the App and the Server part. So whatever works best for you is the right way. Performance-wise, joining strings on one side and splitting them on the other side is not the best, but it also depends on how many entries there are in your array.
Post a Comment for "Creating Json Array From Arraylist Android"