I got this part inside my json object. But I couldn't get this as a java List. It give error. So I tried to take it as a String Array. But it was same as before. So what should I use to parse this data to use with my android application ?
cuisine: {
-cuisine_names: [
"All (36)"
"Malaysian/ Singaporean (1)"
"Asian (1)"
"Australian (2)"
"Chinese (1)"
"European (3)"
"Spanish (1)"
"Greek (2)"
"Steak House (1)"
"Indian (1)"
"International (7)"
"Thai (1)"
"Italian (8)"
"Modern Australian (7)"
]
-price_ranges: [
"Any Price"
"$0-15"
"$15-30"
"$30+"
]
-times: [
"Any Time"
"05:30PM"
"06:00PM"
"06:30PM"
"07:00PM"
"07:30PM"
"08:00PM"
"08:30PM"
"09:00PM"
"09:30PM"
"10:00PM"
"10:30PM"
"11:00PM"
"11:30PM"
]
}
Thanks in advance !
To fill a list with a JSONObject, you should use a function like this (where NewsBSR is a custom object with some basic fields):
private ArrayList<NewsBSR> getListObjectsNews(JSONObject objNews)
{
ArrayList<NewsBSR> listNews = new ArrayList<NewsBSR>();
try{
for (Iterator iterator = objNews.keys(); iterator.hasNext();)
{
String cle = String.valueOf(iterator.next());
Object objet = objNews.get(String.valueOf(cle));
Log.v("V", "News: "+cle+ " : "+objet.toString());
if (cle.equals("results"))
{
JSONArray array = objNews.getJSONArray(cle);
for(int i = 0; i < array.length() ; i++)
{
Object obj = array.get(i);
Iterator it = ((JSONObject) obj).keys();
NewsBSR news = new NewsBSR();
while (it.hasNext())
{
String k = String.valueOf(it.next());
String val = ((JSONObject) obj).getString(k);
Log.v("V", "Array content : "+k+ " : "+val);
if (k.equals("tt") && val.length() > 0)
{
news.setTitle(val);
}
if (k.equals("dt") && val.length() > 0)
{
news.setDate(UtilsDate.stringToDate(val));
}
if (k.equals("num") && val.length() > 0)
{
news.setId(val);
}
}
listNews.add(news);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v("V", "Error HOME: "+ e.getMessage());
e.printStackTrace();
}
return (listNews);
}
I think you have forgotten put commas. And you can use this
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
The json format is not supposed to be like that.
first, there should be a root object surrounding the codes like this.
{ <---this
cuisine: {
-cuisine_names: [
"All (36)"........
} <-- and this
and then you need commas between every string in the array like so
"Australian (2)",
"Chinese (1)",
"European (3)",
"Spanish (1)",
"Greek (2)",
"Steak House (1)",
It's very simple with Gson:
public class Foo
{
static String jsonInput =
"{" +
"\"cuisine\": {" +
"\"cuisine_names\": [" +
"\"All (36)\"," +
"\"Malaysian/ Singaporean (1)\"," +
"\"Asian (1)\"," +
"\"Australian (2)\"," +
"\"Chinese (1)\"," +
"\"European (3)\"," +
"\"Spanish (1)\"," +
"\"Greek (2)\"," +
"\"Steak House (1)\"," +
"\"Indian (1)\"," +
"\"International (7)\"," +
"\"Thai (1)\"," +
"\"Italian (8)\"," +
"\"Modern Australian (7)\"" +
"]," +
"\"price_ranges\": [" +
"\"Any Price\"," +
"\"$0-15\"," +
"\"$15-30\"," +
"\"$30+\"" +
"]," +
"\"times\": [" +
"\"Any Time\"," +
"\"05:30PM\"," +
"\"06:00PM\"," +
"\"06:30PM\"," +
"\"07:00PM\"," +
"\"07:30PM\"," +
"\"08:00PM\"," +
"\"08:30PM\"," +
"\"09:00PM\"," +
"\"09:30PM\"," +
"\"10:00PM\"," +
"\"10:30PM\"," +
"\"11:00PM\"," +
"\"11:30PM\"" +
"]" +
"}" +
"}";
public static void main(String[] args)
{
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
CuisineContainer cc = gson.fromJson(jsonInput, CuisineContainer.class);
System.out.println(cc);
}
}
class CuisineContainer
{
private Cuisine cuisine;
#Override
public String toString()
{
return cuisine.toString();
}
}
class Cuisine
{
private String[] cuisine_names;
private String[] price_ranges;
private String[] times;
#Override
public String toString()
{
StringBuilder result = new StringBuilder();
result.append("cuisine_names: ");
result.append(Arrays.asList(cuisine_names));
result.append(System.getProperty("line.separator"));
result.append("price_ranges: ");
result.append(Arrays.asList(price_ranges));
result.append(System.getProperty("line.separator"));
result.append("times: ");
result.append(Arrays.asList(times));
return result.toString();
}
}
output:
cuisine_names: [All (36), Malaysian/ Singaporean (1), Asian (1), Australian (2), Chinese (1), European (3), Spanish (1), Greek (2), Steak House (1), Indian (1), International (7), Thai (1), Italian (8), Modern Australian (7)]
price_ranges: [Any Price, $0-15, $15-30, $30+]
times: [Any Time, 05:30PM, 06:00PM, 06:30PM, 07:00PM, 07:30PM, 08:00PM, 08:30PM, 09:00PM, 09:30PM, 10:00PM, 10:30PM, 11:00PM, 11:30PM]
Related
I have a problem reading string from JSONArray. the try-catch surrounding the code fire an error for element not found. I suspect it is related with the whitespace that is the character at the end of each key of the rows.
JSONArray dettaglio = result.getJSONArray("dettaglioAttivita");
for(int i = 0; i <dettaglio.length(); i++){
JSONObject row = dettaglio.getJSONObject(i);
String durata = row.getString("Durata ");
Toast.makeText(getApplicationContext(), durata.toString(), Toast.LENGTH_LONG).show();
}
JSON RESPONSE: Note that key string of JSONObject have a whitespace at the end.
"dettaglioAttivita": [
{
"Unità Dididattica ": " FISICA - MODULO A - [UD-1] ",
"Tipo Attività ": " LEZ",
"Tipo Formaz. ": " Base",
"Settore ": " FIS/01 - FISICA SPERIMENTALE",
"CFU ": " 6",
"Durata ": " 48"
},
{
"Unità Dididattica ": " FISICA - MODULO B - [UD-2] ",
"Tipo Attività ": " LEZ",
"Tipo Formaz. ": " Base",
"Settore ": " FIS/01 - FISICA SPERIMENTALE",
"CFU ": " 6",
"Durata ": " 48"
}
],
the exception is:
org.json.JSONException: no value for Durata
Just tested in kotlin and for me it`s working with spaces:
import org.json.JSONObject
fun main(args : Array<String>) {
val json = """
{
"dettaglioAttivita": [
{
"UnitàDididattica ":"FISICA - MODULO A - [UD-1]",
"TipoAttività ":"LEZ",
"TipoFormaz. ":"Base",
"Settore ": "FIS/01 - FISICA SPERIMENTALE",
"CFU":" 6",
"Durata ":" 48"
},
{
"UnitàDididattica ":"FISICA - MODULO B - [UD-2]",
"TipoAttivit à":"LEZ",
"TipoFormaz ":"Base",
"Settore ":"FIS/01 - FISICA SPERIMENTALE",
"CFU ":"6",
"Durata ":" 48"
}
]
}
"""
println(json)
try {
val jsonObject = JSONObject(json)
val dettaglio = jsonObject.getJSONArray("dettaglioAttivita")
for (i in 0 until dettaglio.length()) {
val row = dettaglio.getJSONObject(i)
println("ROW: $row")
val durata = row.getString("Durata ")
println("DURATA: $durata")
}
}catch (e : Throwable){
println(e.toString())
}
}
Printed out in for:
ROW: {"Durata ":" 48","UnitàDididattica ":"FISICA - MODULO A - [UD-1]","TipoFormaz. ":"Base","CFU":" 6","TipoAttività ":"LEZ","Settore ":"FIS/01 - FISICA SPERIMENTALE"}
DURATA: 48
ROW: {"Durata ":" 48","CFU ":"6","UnitàDididattica ":"FISICA - MODULO B - [UD-2]","TipoFormaz ":"Base","TipoAttivit à":"LEZ","Settore ":"FIS/01 - FISICA SPERIMENTALE"}
DURATA: 48
i am accessing data from database and store in arraylist but at the end i display complete list it display null
Output :
09-01 17:26:49.550: E/data(16620): ---->15
09-01 17:26:49.550: > E/data(16620): ---->[[], [], [], [], [], [], [],
[], [], [], [], [], [], [], []]
public static ArrayList<ArrayList<HashMap<String, String>>> testdata(SQLiteDatabase db)
{
int count=0;
int k=0;
ArrayList<ArrayList<HashMap<String, String>>> data =
new ArrayList<ArrayList<HashMap<String,String>>>();
ArrayList<HashMap<String, String>> odata =
new ArrayList<HashMap<String,String>>();
String Query=
"SELECT * FROM myfiles "+
"WHERE (( Datetime('2014-09-01 09:50:15') >= startdate " +
"AND Datetime('2014-09-01 09:50:15') <= enddate ) " +
"AND ( " +
"('09:50:15' >= strftime('%H:%M:%S',timer_from) " +
"AND '09:50:15' <= strftime('%H:%M:%S',timer_to )) " +
"OR ( strftime('%H:%M:%S',timer_from) = '00:00:00' " +
"OR '00:00:00' = strftime('%H:%M:%S',timer_to )))) " +
"AND ( Monday = 1 OR Everyday = 1) AND download = 1 " +
"AND playlist_id = 24 AND user_id='83' " +
"ORDER BY position_id ASC, subposition_id ASC";
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount()<=0)
{
cursor.close();
return data;
}
else
{
if (cursor.moveToFirst())
{
do
{
HashMap<String, String> map = new HashMap<String, String>();
String currenttype=cursor.getString(9);
String nexttype = null;
if(count<cursor.getCount())
{
if(cursor.getPosition()==cursor.getCount()-1)
{
nexttype="image";
}
else
{
cursor.moveToNext();
nexttype=cursor.getString(9);
cursor.moveToPrevious();
}
}
map.put(DB_Constant.MYFILES.FILE_ID, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_ID)));
map.put(DB_Constant.MYFILES.FILE_TYPE, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_TYPE)));
map.put(DB_Constant.MYFILES.FILE_SUBTYPE, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_SUBTYPE)));
map.put(DB_Constant.MYFILES.FILE_PATH, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_PATH)));
map.put(DB_Constant.MYFILES.USERID, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.USERID)));
map.put(DB_Constant.MYFILES.FILE_SECOND, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_SECOND)));
map.put(DB_Constant.MYFILES.FILE_DOWNLOAD, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_DOWNLOAD)));
map.put(DB_Constant.MYFILES.FILE_STARTTIME, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_STARTTIME)));
map.put(DB_Constant.MYFILES.FILE_ENDTIME, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_ENDTIME)));
map.put(DB_Constant.MYFILES.FILE_TIMERFROM, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_TIMERFROM)));
map.put(DB_Constant.MYFILES.FILE_TIMERTO, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_TIMERTO)));
map.put(DB_Constant.MYFILES.FILE_STUDIOFORMAT, cursor.getString(cursor.getColumnIndex(DB_Constant.MYFILES.FILE_STUDIOFORMAT)));
odata.add(map);
if(currenttype.equalsIgnoreCase("image") ||
currenttype.equalsIgnoreCase("video"))
{
data.add(odata);
odata.clear();
}
else if(nexttype.equalsIgnoreCase("image") ||
nexttype.equalsIgnoreCase("video"))
{
data.add(odata);
odata.clear();
}
count++;
} while (cursor.moveToNext());
}
}
Log.e("data","---->"+data.size());
Log.e("data","---->"+data);
cursor.close();
return data;
}
When you add an element to a Map, a List or a Set, the original object is added, no copy is created, so if you modify it, it is modified within the collection. Simple example:
class Foo {
public int bar;
}
using that simple class in another piece of code...
List<Foo> myList= new ArrayList<>();
Foo f= new Foo(); //we create a Foo object, and f is a variable that references it
f.bar=9;
myList.add(f); //we add the object to the list
So now we have two references to this object: f and myList.get(0). If you do:
f.bar=15;
then
System.out.println(myList.get(0))
will show 15 in your screen.
In your code you are reusing the same object. Instead calling clear(), create a new object:
odata = new ArrayList<HashMap<String,String>>();
In sum: you can reuse a variable, but in that case you cannot reuse the referenced object.
You have successfully added your hashmap to your list. And the count shows 15 as well. The only problem is, you are not being able to either store correctly on hash map or display correctly
What are good practice for handling json over a Rest Framework in Android. For instance, if I get a certain json result as follow (or any other, I'm just giving something more complex):
{"lifts":
[{
"id":26,
"time":"2012-11-21T12:00:00Z",
"capacity":4,
"price":10,
"from": {
"description":null,
"city": {
"name":"Montreal"
}
},
"to":{
"description":"24 rue de la ville",
"city":{
"name":"Sherbrooke"
}
},
"driver":{
"first_name": "Benjamin",
"image":"https://graph.facebook.com/693607843/picture?type=large"
}
}
]}
1) Should I handle the result manually and get each value to populate my ui... (Not really)
2) Should I create a POJO for each object (to handle the mapping, with JSONObject). In my example, I will have to create a lift object that handle all the parameters and even create more POJO, to use for instance image and probably locations. (so basically, I constantly need to check my api rest framework to see how my object are done on server side, I'm duplicating my models from server to the android client).
3) Is there any framework to handle the mapping (serialize and deserialization).
I'm currently using option number 2, but was wondering if there was something better out there. It's working for me so far, for receiving and sending.
I like to create a response object per api endpoint where i map the response of the call.
For the given example and using GSON, the response object would be something like the following
public class Test
{
static String jsonString =
"{\"lifts\":" +
" [{" +
" \"id\":26," +
" \"time\":\"2012-11-21T12:00:00Z\"," +
" \"capacity\":4," +
" \"price\":10," +
" \"from\": { " +
" \"description\":null," +
" \"city\": {" +
" \"name\":\"Montreal\"" +
" }" +
" }," +
" \"to\":{" +
" \"description\":\"24 rue de la ville\"," +
" \"city\":{" +
" \"name\":\"Sherbrooke\"" +
" }" +
" }," +
" \"driver\":{" +
" \"first_name\": \"Benjamin\"," +
" \"image\":\"https://graph.facebook.com/693607843/picture? type=large\"" +
" }" +
" }" +
" ]}";
public static void main( String[] args )
{
Gson gson = new Gson();
Response response = gson.fromJson( jsonString, Response.class );
System.out.println( gson.toJson( response ) );
}
public class Response
{
#SerializedName("lifts")
List<Lift> lifts;
}
class Lift
{
#SerializedName("id")
int id;
#SerializedName("time")
String time;
#SerializedName("capacity")
int capacity;
#SerializedName("price")
float price;
#SerializedName("from")
Address from;
#SerializedName("to")
Address to;
#SerializedName("driver")
Driver driver;
}
class Address
{
#SerializedName("description")
String description;
#SerializedName("city")
City city;
}
class City
{
#SerializedName("name")
String name;
}
class Driver
{
#SerializedName("first_name")
String firstName;
#SerializedName("image")
String image;
}
}
I want to convert JSON into java code. My jsoncode as per given below.
{
"nodes": [
{
"node": {
"Name": "rahul Patel",
"Address": "\n\tAhmedabad",
"Date of Birth": "1991-05-03",
"Occupation": "developer",
"Member Since": "3 weeks 4 days"
}
}
]
java code
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse
.getJSONArray(nodes);
System.out.println("=hello this is DoinBackground");
for (i = 0; i < jsonnodes.length(); i++) {
System.out.println("hello this is for loop of DoinBackground");
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode
.getJSONObject(node);
bean = new UserProfileBean();
bean.name = jsonnodevalue.getString(Name);
listActivities.add(bean);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Here in logcat I print the value of before for loop System.out.println("=hello this is DoinBackground");,but value can't print under the for loop System.out.println("hello this is for loop of DoinBackground");
NOTE: Please let me know, Is it possible that we cannot used for loop in the code ? if yes then give the solution for that, There is another solution for this given problem.
Thanks.
Your json string is wrong. It must be trminated with }. Fix this and it will work.
Fixed json string:
{
"nodes": [
{
"node": {
"Name": "rahul Patel",
"Address": "\n\tAhmedabad",
"Date of Birth": "1991-05-03",
"Occupation": "developer",
"Member Since": "3 weeks 4 days"
}
}
]
}
Sample code to test:
String j = "{\r\n" +
" \"nodes\": [\r\n" +
" {\r\n" +
" \"node\": {\r\n" +
" \"Name\": \"rahul Patel\",\r\n" +
" \"Address\": \"\\n\\tAhmedabad\",\r\n" +
" \"Date of Birth\": \"1991-05-03\",\r\n" +
" \"Occupation\": \"developer\",\r\n" +
" \"Member Since\": \"3 weeks 4 days\"\r\n" +
" }\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
try{
JSONObject objResponse = new JSONObject(j);
JSONArray jsonnodes = objResponse.getJSONArray("nodes" );
for (int i = 0; i < jsonnodes.length(); i++) {
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode
.getJSONObject("node");
Log.v("name", jsonnodevalue.getString("Name"));
Log.v("address", jsonnodevalue.getString("Address"));
Log.v("occupation", jsonnodevalue.getString("Occupation"));
}
}
catch (Exception e) {
e.printStackTrace();
}
Try using Gson - http://code.google.com/p/google-gson/. Will save a lot of headache.
In your code, however make sure that your JSON string is being parsed properly.
Just to be sure objResponse.getJSONArray(nodes) should be objResponse.getJSONArray("nodes")
I am having a problem when I create an array of strings, this only happens in 2.1 android api level 7 or lower and i need to install the application on a device with exactly this configuration, any idea how to solve the problem?
Below the source code, the message that pops up on screen and also logcat's message.
CODE:
private String[] fillPedidosName() {
TipoPedidoDAO tipoDAO = null;
try {
tipoDAO = new TipoPedidoDAO();
pedidosList = tipoDAO.selectAll();
String[] temp = new String[pedidosList.size()];
for (int i = 0; i < pedidosList.size(); i++) {
if (pedidosList.get(i) != null) {
temp[i] = pedidosList.get(i).getDescricao().toString();
}
}
return temp;
} catch (Exception ex) {
MyLoger.logar(ex);
return null;
} finally {
if (tipoDAO.getDB().isOpen()) {
tipoDAO.closeConnection();
}
}
}
THE MESSAGE THAT POPS UP DEBUGING:
Exception processing async thread queue
Exception processing async thread queue
java.lang.UnsupportedOperationException
lOGCAT'S MESSAGE:
03-03 17:57:57.124: ERROR/jdwp(1267): REQ: UNSUPPORTED (cmd=2/11 dataLen=8 id=0x0012ba)
You are probably not using a List that supports get(int).
Try changing your List implementation to ArrayList. When you create your list:
List myList = new ArrayList()
This is probably happening inside tipDAO.selectAll().
I had this problem. I got it fixed.
When working with Arrays of your Objects, make sure you have defined a constructor in the object file.
This piece of code was creating the error
List<Prediction> predictions = new ArrayList<Prediction>();
The fix.
Prediction class file was missing a constructor. After putting in a default constructor, the error is gone for me.
package com.thuptencho.torontotransitbus.models;
public class Prediction {
public String epochTime = "", seconds = "", minutes = "", isDeparture = "", affectedByLayover = "", branch = "",
dirTag = "", vehicle = "", block = "", tripTag = "";
//this constructor was missing..after coding this constructor. the error was gone.
public Prediction(){
super();
}
#Override
public String toString() {
return "epochTime:" + this.epochTime + " seconds:" + this.seconds + " minutes:" + this.minutes
+ " isDeparture:" + this.isDeparture + " affectedByLayover:" + this.affectedByLayover + " branch:"
+ this.branch + " dirTag:" + this.dirTag + " vehicle:" + this.vehicle + " block:" + this.block
+ " triptag:" + this.tripTag;
}
}