Pass a TreeMap from one activity to other - android

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

Related

Unable to Parse Nested JSON object

I want to retrieve "opening_hour" object and parse "open_now" array. But I am unable to do that for some reason, may be my parsing hierarchy is wrong. Can someone suggest, how should it be. Below is my JSON link :
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.9647254,77.7191899&radius=500&name=cafe&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
}
JSONArray jarraytwo = jsono.getJSONArray("opening_hours");
for (int i = 0; i < jarraytwo.length(); i++) {
JSONObject objecttwo = jarraytwo.getJSONObject(i);
Elements parameterstwo = new Elements();
parameterstwo.setAuthor(objecttwo.getString("open_now"));
Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();
elementListtwo.add(parameterstwo);
}
return true;
This is dumb question I know but I am unaware of nested json parsing. Below is my full code and link from where I am passing
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
private GoogleApiClient googleApiClient;
int status;
ArrayList<String> result;
ArrayList<Elements> elementList;
ArrayList<Elements> elementListtwo;
ElementAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Welcome to Harman Framework");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//mVoiceInputTv.setText(result.get(0));
Toast.makeText(getApplicationContext(), "You searched : " + result.get(0), Toast.LENGTH_LONG).show();
elementList = new ArrayList<Elements>();
new JSONAsyncTask().execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ElementAdaptor(getApplicationContext(), R.layout.row, elementList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
Intent intent = new Intent(getApplicationContext(), DescriptionActivity.class);
intent.putExtra("title", elementList.get(position).getTitle());
intent.putExtra("author", elementList.get(position).getAuthor());
intent.putExtra("publishedat", elementList.get(position).getPublishedat());
intent.putExtra("description", elementList.get(position).getDescription());
intent.putExtra("imageurl", elementList.get(position).getImage());
startActivity(intent);
}
});
}
break;
}
}
}
//String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk";
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading.......");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpParams params = httpclient.getParams();
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
}
return true;
}
} catch (JSONException e3) {
e3.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
You need to nest your for loops into each other. Take a look at the structure of your JSON-File: You have your jarray, which is an Array of JSON Objects. Each of these JSON Objects in the array have it's own opening hours. So you want somethin like this:
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
// Get opnening hours for current result
JSONObject curOpeningHours = object.getJSONObject("opening_hours");
hoursList.push(curOpeningHours);
String openNow = curOpeningHours.getString("open_now");
// Do something...
}
It did not test this, but it should give you an idea
Use nested JSONObject
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
JSONArray jarray1 = object.getJSONArray("opening_hours");
for (int j = 0; j < jarray1.length(); j++) {
JSONObject object2 = jarray1.getJSONObject(j);
parameters.setOpenNow(object2.getString("open_now"));
}
}
I wouldn't use JSONObject at all when parsing a complex json or if the json at least contains an array of objects.
Instead use google-gson.
Using gson you can serialize/deserialize your json with less code and effort.
I would first create a java class that represents the same json scheme you're trying to parse.
for example, trying to parse this JSon String:
[
{
"FirstName": "What",
"LastName": "Ever"
},
{
"FirstName": "John",
"LastName": "Snow"
}
]
In java code, I would first create a class:
public class Person {
public String FirstName;
public String LastName;
}
Now to parse the json:
Gson gson = new Gson();
List<Person> people = gson.fromJson("Json string here", new TypeToken<List<Person>>() {}.getType());
Now you can simply do a loop on the list, and find John Snow.

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

JSON is returning strange characters in Android

I implemented an app that gets data from a JSON. JSON is returning me characters:
Âé...
How I can get that return JSON:
áéíóú
instead of
Âé
private void parseJson(JSONObject json) {
nombresLista = new ArrayList<HashMap<String, String>>();
if (json != null){
try {
JSONArray sitios = json.getJSONArray("sites");
for (int i = 0; i < sitios.length(); i++) {
JSONObject jsonObj = sitios.getJSONObject(i);
String nombre = jsonObj.getString("name");
HashMap<String, String> lista = new HashMap<String, String>();
lista.put("name", nombre);
nombresLista.add(lista);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < nombresLista.size(); i++) {
String nombre = nombresLista.get(i).get("name");
Log.e("", "nombre = " + nombre);
}
}

Stop creating fragmnet view until i have parsed all data from Json.

I receive a null pointer exeception when trying to populate the interface beacuse I have no data in my instance object.
I am using a login button and call a service, i receive a json and after I parse it i have a status handler...login ok... Here I want to start an asynk task to get some photo data
public void StatusHandlerLogin(String status, Activity currentActivity) {
if (status.equals("0")) {
new GetPhotoDataTask(currentActivity).execute();
Intent intent = new Intent(currentActivity,
NavigationActivity.class);
currentActivity.startActivity(intent);
}
//}
The asynk task is like this
public class GetPhotoDataTask extends
AsyncTask<Void, Void, List<PhotoData>> {
Activity activity;
public GetPhotoDataTask(Activity activity) {
this.activity = activity;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
Log.d("GetPhotoDataTask onPreExecute",
"GetPhotoDataTask onPreExecute");
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
#Override
protected List<PhotoData> doInBackground(Void... params) {
Log.d("GetPhotoDataTask doInBackground",
"GetPhotoDataTask doInBackground");
MyStyleApi myStyleApi = new MyStyleApi();
List<PhotoData> photoData = null;
try {
photoData = myStyleApi.getPhotoDataWithDispatch();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> photoStr = new ArrayList<String>();
for (int i = 0; i < photoData.size(); i++) {
photoStr.add(photoData.get(i).getPhotoURL());
}
String[] photoUrls = new String[photoStr.size()];
photoUrls = photoStr.toArray(photoUrls);
for (int i = 0; i < photoUrls.length; i++) {
if (photoUrls[i].contains("\"")) {
photoUrls[i] = photoUrls[i].replace("\"", "");
}
}
AppManager.getInstance().setphotoUrls(photoUrls);
List<PhotoData> photoDataS = AppManager.getInstance().setPhotoData(
photoData);
return photoData;
}
protected void onProgressUpdate(Integer... percent) {
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
protected void onPostExecute(List<PhotoData> photoData) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
on do in background i have a method that call other service
get PhotoData with userId as param
public List<PhotoData> getPhotoDataWithDispatch() throws JSONException,
ClientProtocolException, IOException {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
UserData data = AppManager.getInstance().getUserData();
String userID = data.getUserID();
if (userID.contains("\"")) {
userID = userID.replace("\"", "");
}
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("userID", userID);
JsonArray response = WebServiceApi.PostToServiceWithStringResponse(
"images/get_images_data", params);
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
if (response != null) {
photoDataList = parseJsonArrayForFotoData(response);
}
return photoDataList;
}
and if response is not null i parse it
public static List<PhotoData> parseJsonArrayForFotoData(JsonArray jsonArray) {
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
for (int i = 0; i < jsonArray.size(); i++) {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
JsonElement photoID = ((JsonObject) jsonArray.get(i)).get("pozaID");
JsonElement photoUrl = ((JsonObject) jsonArray.get(i))
.get("pozaURL");
JsonElement thumbURL = ((JsonObject) jsonArray.get(i))
.get("thumbURL");
JsonElement tags = ((JsonObject) jsonArray.get(i)).get("tags");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(tags.toString()).getAsJsonArray();
List<Tags> tagsList = new ArrayList<Tags>();
for (int j = 0; j < array.size(); j++) {
JsonElement tagId = ((JsonObject) array.get(j)).get("tagID");
JsonElement coordX = ((JsonObject) array.get(j)).get("coordX");
JsonElement coordY = ((JsonObject) array.get(j)).get("coordY");
JsonElement productId = ((JsonObject) array.get(j))
.get("productID");
Tags tagPData = new Tags(tagId.toString(), coordX.toString(),
coordY.toString(), productId.toString());
tagsList.add(tagPData);
}
PhotoData photoData = new PhotoData(photoID.toString(),
photoUrl.toString(), thumbURL.toString(), null, tagsList);
photoDataList.add(photoData);
}
return photoDataList;
}
ok in GetPhotoDataTaskFb do in background i set the instance of the photos object
AppManager.getInstance().setphotoUrls(photoUrls);
and in fragmnet
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ac_image_pager, container,
false);
// Dummy code
if (counter == 0) {
for (int i = 0; i <= 20; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
counter++;
String[] imageUrls = AppManager.getInstance().getphotoUrls();
//here is where i get the null.. i tried some dummy code to delay and receive data but it is not working
How can I manage to stop create view until all data is parsed?

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

Categories

Resources