Convert JSONArray into a String Array [closed] - android

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

Related

array of objects

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

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

Having issue while parsing Json volley request

this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}

How to combine to json arrays

In order to combine 2 JSON arrays into one I use the following code (the input data areJSON arrays that wereconverted to a string)
private static String combineData(String Data, String data){
if (empty(data))
data = Data;
else { // need to append the data
try {
// first, convert the strings back to JSON objects
JSONObject jsonObj1 = new JSONObject(data); // existing data
JSONObject jsonObj2 = new JSONObject(Data); // new data
// Getting Array of Providers
String fieldName = context.getString(R.string.JSON_COMP_RECORDS);
// Second, get the array out of the JSON object
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
// Third, join them into one array
JSONArray arr = new JSONArray();
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record2.length(); i++) {
JSONObject c;
try {
c = record2.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
JSONObject json = new JSONObject();
json.put (context.getString(R.string.JSON_COMP_RECORDS), arr);
data = json.toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
return data;
}
I wonder if there is a way to do it more efficiently and get rid of the 2 loops?
How about this ? You can put JSONObject directly int another array
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
record2.put (c);
}
Hope this helps
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
record2.put(record1.getJSONObject(i));
}

Pass a TreeMap from one activity to other

I have a
TreeMap<String, ArrayList<Video>> mShows = new TreeMap<String, ArrayList<Video>>();
and I'm trying to pass from one activity to another. I have tried
"putExtra treeMap returns HashMap cannot be cast to TreeMap android"
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
Bundle bun = i.getBundleExtra("lascategorias");
mCategories = bun.getStringArray("categories");
mShows = new TreeMap<String, ArrayList<Video>>(Map<String,ArrayList<Video>> getIntent().getExtras().get("map"));
}
but it says that Map, String and the ArrayList cannot be resolved to a variable where I have (Map>)
This is how I add it
protected void onPostExecute(final String json) {
Log.i(LOG_TAG, "decoding...");
if (json == null)
return;
try {
final URI base = new URI(mUrl);
final JSONObject jso = new JSONObject(json);
final JSONArray ja = jso.getJSONArray("categories");
for (int i = 0; i < ja.length(); i++) {
final JSONObject list = ja.getJSONObject(i);
final ArrayList<Video> vidList = new ArrayList<Video>(10);
mShows.put(list.getString("name"), vidList);
final JSONArray videos = list.getJSONArray("videos");
for (int j = 0; j < videos.length(); j++) {
final JSONObject vids = videos.getJSONObject(j);
final JSONArray sources = vids.getJSONArray("sources");
try {
final Video v = new Video(base.resolve(vids.getString("thumb")),
base.resolve(sources.getString(0)), vids.getString("title"),
vids.getString("subtitle"), vids.getString("description"));
vidList.add(v);
// The rare case that I've got more than one
for (int k = 1; k < sources.length(); k++) {
v.mSource.add(base.resolve(sources.getString(k)));
}
} catch (IllegalArgumentException expected) {
Log.e(LOG_TAG, "Bad Json.");
}
}
}
} catch (final JSONException je) {
Log.e(LOG_TAG, "An error in the JSON." + je.getMessage());
} catch (final URISyntaxException se) {
Log.e(LOG_TAG, "URI syntax error" + se.getMessage());
}
//onDataComplete();
mCategories = getCategories();
Bundle b = new Bundle();
b.putStringArray("categories", mCategories);
//b.p
Intent i = new Intent("com.video.tv.MainActivity" );
i.putExtra("las Categorias", b);
i.putExtra("map", mShows);
startActivity(i);
finish();
}
}
I declared mShows earlier
public TreeMap<String, ArrayList<Video>> mShows = new TreeMap<String, ArrayList<Video>>();
There's one closing bracket missing, just before getIntent(). Correct form:
mShows = new TreeMap<String, ArrayList<Video>>((TreeMap<String, ArrayList<Video>>) getIntent().getExtras().get("map"));

Categories

Resources