parse JsonArray in android - android

How to parse this jsonarray "Images" ??
I parse this json ,, but i can't get "Images"
the Jsonarray "data" inside it elements , inside every element array of images >>>>
this is the response
this is my code
JSONObject responseObject = new JSONObject(response);
JSONArray newsJsonArray = responseObject.getJSONArray("data");
final List <AndroidVersion> newsList = new ArrayList <AndroidVersion>();
newsImages = new ArrayList<String>();
newsids = new ArrayList<String>();
newsnames = new ArrayList<String>();
newshotelsid = new ArrayList<String>();
newscontents = new ArrayList<String>();
newstimesto = new ArrayList<String>();
newscost = new ArrayList<String>();
newstimesfrom = new ArrayList<String>();
newscountry = new ArrayList<String>();
newscity = new ArrayList<String>();
newstype = new ArrayList<String>();
newsImages = new ArrayList<String>();
for (int j = 0; j < newsJsonArray.length(); j++) {
AndroidVersion news = new AndroidVersion();
if (newsJsonArray.getJSONObject(j).has("id")) {
newsids.add(newsJsonArray.getJSONObject(j).getString("id"));
}
if (newsJsonArray.getJSONObject(j).has("name")) {
news.setName(newsJsonArray.getJSONObject(j).getString("name"));
newsnames.add(newsJsonArray.getJSONObject(j).getString("name"));
}
if (newsJsonArray.getJSONObject(j).has("desc")) {
news.setdesc(newsJsonArray.getJSONObject(j).getString("desc")
.replaceAll("<p>", "").replaceAll("<\\/p>\\r\\n", "").replaceAll(" ", ""));
newscontents.add(newsJsonArray.getJSONObject(j).getString("describtion"));
}
if (newsJsonArray.getJSONObject(j).has("country")) {
news.setcountry(newsJsonArray.getJSONObject(j).getString("country"));
newscountry.add(newsJsonArray.getJSONObject(j).getString("country"));
}
if (newsJsonArray.getJSONObject(j).has("city")) {
news.setcity(newsJsonArray.getJSONObject(j).getString("city"));
newscity.add(newsJsonArray.getJSONObject(j).getString("city"));
}
if (newsJsonArray.getJSONObject(j).has("date_from")) {
news.setdate_from(newsJsonArray.getJSONObject(j).getString("date_from"));
newstimesfrom.add(newsJsonArray.getJSONObject(j).getString("date_from"));
}
if (newsJsonArray.getJSONObject(j).has("date_to")) {
news.setdate_to(newsJsonArray.getJSONObject(j).getString("date_to"));
newstimesto.add(newsJsonArray.getJSONObject(j).getString("date_to"));
}
if (newsJsonArray.getJSONObject(j).has("num persons")) {
news.sethotel_id(newsJsonArray.getJSONObject(j).getString("num persons"));
newshotelsid.add(newsJsonArray.getJSONObject(j).getString("num persons"));
}
if (newsJsonArray.getJSONObject(j).has("price")) {
news.setprice(newsJsonArray.getJSONObject(j).getString("price"));
newscost.add(newsJsonArray.getJSONObject(j).getString("price"));
}
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
newsList.add(news);
}

I would highly recommend using Gson to parse it.
Create a response object with structure matching the json response. Then you can use the single object without having to create it down into parts.

Change this part:
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
to:
if(newsJsonArray.getJSONObject(j).getJSONArray("images") != null) {
JSONArray jArray = newsJsonArray.getJSONObject(j).getJSONArray("images");
for (int k=0; k<jArray.length(); k++) {
news.setImage(jArray.getString(k));
newsImages.add(jArray.getString(k));
}
}

You can use direct string object from JSONArray like below:
JSONArray array = object.getJSONArray("images");
for (int i = 0; i < array.length(); i++) {
String image = array.getString(i);
}

Related

How To store json values in a set of arrays in android

i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}

Android get elements from json array

I'm trying to get elements from my json array.
this is my json response:
{"IDs":["635426812801493839","635429094450867472","635433640807558204"]}
This is what I've tried so far:
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
JSONObject obj = a.getJSONObject(i);
stringArray.add(obj.toString());
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());
But I'm getting empty list. What is wrong with my code? Any help will be truly appreciated. Thanks.
The for loop should be
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
your the JSONArray contains already string
JSONObject obj = a.getJSONObject(i);
replace with
String str = a.getString(i);
Use this
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());

Insert JSON Array on String Array on android

I have JSON array like below format
{
"get": [],
"post": {
"_event": "get_buyers_guide_detail",
"_deviceID": "490154203237518",
"type": "cars",
"model_id": "1007"
},
"cars": [
{
"ID": 6119,
"post_title": "COROLLA",
"interior_images": [
"http://.....e8664969d20654bf2a58f1b26de70d2.jpg",
"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg",
"http://........1d14a554a2ed78d1659463ec.jpg"
],
}
]
}
I have create JSONArray for this:
JSONArray Array = entries.getJSONArray("cars");
for (int i = 0; i < Array.length(); i++) {
JSONObject detailObject = Array.getJSONObject(i);
String ID = detailObject.getString("ID");
String title = detailObject.getString("post_title");
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
// What to do here ????
}
}
now i am confused with this format of JSON data. There is no JSONObject to get the values. How to insert these string on Array please help me find out the solution
Try this,
galleryArray.getString(j);
this should get the string at position j.
galleryArray.getString(index);
This function will return String object of corresponding index
try this
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
try {
JSONObject jsonObject = galleryArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Try this way,hope this will help you to solve your problem.
try{
String jsonRespone="{\"get\":[],\"post\":{\"_event\":\"get_buyers_guide_detail\",\"_deviceID\":\"490154203237518\",\"type\":\"cars\",\"model_id\":\"1007\"},\"cars\":[{\"ID\":6119,\"post_title\":\"COROLLA\",\"interior_images\":[\"http://.....e8664969d20654bf2a58f1b26de70d2.jpg\",\"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg\",\"http://........1d14a554a2ed78d1659463ec.jpg\"],}]}";
JSONObject responeJson = new JSONObject(jsonRespone);
ArrayList<HashMap<String,Object>> data = new ArrayList<HashMap<String, Object>>();
JSONArray carsJsonArray = responeJson.getJSONArray("cars");
for (int i=0;i<carsJsonArray.length();i++){
HashMap<String,Object> row = new HashMap<String, Object>();
row.put("ID",carsJsonArray.getJSONObject(i).getString("ID"));
row.put("TITLE",carsJsonArray.getJSONObject(i).getString("post_title"));
JSONArray galleryArray = carsJsonArray.getJSONObject(i).getJSONArray("interior_images");
ArrayList<String> interiorImages = new ArrayList<String>();
for(int j=0; j<galleryArray.length(); j++){
interiorImages.add(galleryArray.getString(j));
}
row.put("INTERIORIMAGES",carsJsonArray.getJSONObject(i).getString("interiorImages"));
data.add(row);
}
for (HashMap<String,Object> row :data){
System.out.print("ID : "+row.get("ID"));
System.out.print("TITLE : "+row.get("TITLE"));
ArrayList<String> interiorImages = (ArrayList<String>) row.get("INTERIORIMAGES");
for (int j=0;j<interiorImages.size();j++){
System.out.print("INTERIORIMAGES +"+j+" : "+interiorImages.get(j));
}
}
}catch (Throwable e){
e.printStackTrace();
}
I think you need to use List of Map
Example:
List<Map> list = new ArrayList<Map>();
Map map = new HashMap();
map.put("userIcon", R.drawable.scott);
map.put("username", "Shen");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
map = new HashMap();
map.put("userIcon", R.drawable.ricardo);
map.put("username", "Ricardo");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
add this in loop

can't fill array NewsData[] NewsData_data

write Custom ArrayAdapter by example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
i can't fill array in cycle.
working example:
Weather weather_data[] = new Weather[]
{ new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Cloudy"),
new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Showers")
};
my code:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
You need to initialize this array:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data=new NewsData[jsonMainNode.length()];//<------------HERE
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
Simplified answer: your array is not initialized. Longer answer, you have to know how big it is going to be, then initialize it to that size. A simple example:
NewsData[] NewsData_data;
ArrayList<NewsData> newsDataArray = new ArrayList<NewsData>();
String header = "header";
String short_text = "short_text";
String team = "team";
String datatime = "datatime";
String photo_url = "photo_url";
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
NewsData_data = new NewsData[newsDataArray.size()];
newsDataArray.toArray(NewsData_data);
System.out.println(NewsData_data);

how to filter json array by some condition

how to filter values from json array i want to filter that if string zero1check =0 add only that json array in Category_name.add(object.getString("dish_name")); where "day":"m1"
if zero1check =0 add in Category_name.add(object.getString("dish_name")); only that json array which contain "day":"m2"
{
"status":1,
"data":
[
{
"school_name":"testing12",
"menu_title":"Menu1",
"dish_name":null,
"day":"m1"
}
,
{
"school_name":"testing12"
,"menu_title":"Menu1",
"dish_name":null,
"day":"m1"
}
,
{
"school_name":"testing12"
,"menu_title":"Menu1",
"dish_name":null,
"day":"m2"
}
,
{
"school_name":"testing12"
,"menu_title":"Menu1",
"dish_name":null,
"day":"m2"
}
]
}
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
String zero1check;
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] =
school.getJSONObject(k).getString("menu_title");
menu_nametxt.setText(mVal[0]);
}
Try this.. then change zero1check datatype as int
JSONArray school = json2.getJSONArray("data");
for (int i1 = 0; i1 < school.length(); i1++) {
JSONObject object = school.getJSONObject(i1);
if(zero1check == 0)
{
if(object.getString("id").equals("m1"))
{
Category_name.add(object.getString("dish_name"));
}
}
else if(zero1check == 1)
{
if(object.getString("id").equals("m2"))
{
Category_name.add(object.getString("dish_name"));
}
}
}

Categories

Resources