I have this json url which outputs this (snippet)
{
"status":true,
"result":{
"message":"Successfully retrieved the daily feed.",
"items":{
"1376438400":[
{
"code":"DjCr3N3o",
"slug":"soulja-boy-gets-kicked-off-airplane",
"cdn_screenshot_path":"screenshots\/2013\/08\/DjCr3N3o.png",
"title":"Soulja Boy Gets Kicked Off Airplane!",
"hits":"457",
"date_added":"1376507797"
},
{
"code":"7V9eOVpX",
"slug":"dr.-dre-and-suge-knight-baby-mama-michelle-surprise-performance-she-sounds-like-a-chipmunk-but-sings-like-an-angel",
"cdn_screenshot_path":"screenshots\/2013\/08\/7V9eOVpX.png",
"title":"Dr. Dre AND Suge Knight Baby Mama Michel'le Surprise Performance! (She Sounds Like A Chipmunk But Sings Like An Angel!)",
"hits":"525",
"date_added":"1376505010"
},
{
"code":"8ovO203r",
"slug":"headless-snake-bites-itself-in-the-butt",
"cdn_screenshot_path":"screenshots\/2013\/08\/8ovO203r.png",
"title":"Headless Snake Bites Itself In The Butt!",
"hits":"361",
"date_added":"1376485812"
}
],
"1376352000":[
{
"code":"9b9jR6qs",
"slug":"show-you-how-to-do-this-son-chris-paul-hits-4-straight-jumpers-on-colleges-best-point-guards",
"cdn_screenshot_path":"screenshots\/2013\/08\/9b9jR6qs.jpg",
"title":"Show You How To Do This Son! Chris Paul Hits 4 Straight Jumpers On College's BEST Point Guards!",
"hits":"979",
"date_added":"1376443810"
},
{
"code":"p6l5pwg8",
"slug":"ttbnez-fck-da-opp-music-video",
"cdn_screenshot_path":"screenshots\/2013\/08\/p6l5pwg8.png",
"title":"TTBNEZ - F*ck Da Opp [Music Video]",
"hits":"316",
"date_added":"1376419812"
},
{
"code":"haxUoUVt",
"slug":"strip-life-the-reality-series-feat.-lanipop-entyce-trailer",
"cdn_screenshot_path":"screenshots\/2013\/08\/haxUoUVt.png",
"title":"Strip Life: The Reality Series (feat. Lanipop, Entyce) [Trailer]",
"hits":"426",
"date_added":"1376419214"
}
],
The problem I am having is figuring out how to parse it due to its format and how to reach the data such as "code", "slug" and "title". This is what I have so far, but it seems wrong as I may have to have 2 loops instead of 1 I think.
This is what I have so far
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
try {
// Locate the array name
jsonarray = jsonobject.getJSONArray("item");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
You're just missing a little point here!
in here you got the first json object :
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
this json object is the whole big JSON object that contain status and result but you directly want to access the JSON array that inside result object! using this :
// Locate the array name
jsonarray = jsonobject.getJSONArray("items");
The right thing is you must get the result object first from the big json object with
JSONObject resultObject = jsonobject.getJSONObject("result");
then use the resultObject to get the array!
try {
// Locate the array name
jsonarray = resultObject .getJSONArray("item");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
I hope you understand my answer, but if you have other question about my answer feel free to ask! :)
Related
I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.
I have a piece of code which basically synchronises data between an online database. However I am getting an error on one particular line of code (map.put("id", obj.get(mydb.WEB_ID).toString());) where an integer value is obtained from the android sqlite databasse and submitted to the online database. The full cose is as displayed below :
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> syncL;
syncL = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("web_id"));
System.out.println(obj.get("phone_id"));
System.out.println(obj.get("msg_id"));
mydb.updateWebSync(obj.get(obj.get("phone_id").toString(), obj.get("msg_id").toString(), obj.get("web_id").toString());
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", obj.get(mydb.WEB_ID).toString());
map.put("p_id", obj.get(mydb.COLUMN_ID).toString());
map.put("s", "1");
syncL.add(map);
}
updateMySQLSyncSts(gson.toJson(syncL), "syncsts");
Toast.makeText(getApplicationContext(), "Download Messages success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Download Messages error!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
In my android sqlite database, the value of mydb.WEB_ID is stored as an integer. Any assistance is appreciated.
Hashmap<String,String>
it only contains String values. So you have to convert it to String.
with using
toString()
function it ll give you error.
Try with
String.ValueOf(obj.get("web_id"))
it ll convert the interger value to String and your problem gets resolved.
Happy coding. :P
I figured out my mistake...I was calling the database column name in the HashMap which is different from the json variable. Thanks all for your assistance.
I have 2 links; which gives json data. I am trying to get the values from the urls from the same activity in android using asynTask. did the coding till converting the data to string(stored it in jsonStr1). But now comes the problem. Because,among the 2 urls:
one starts with JSON object-
{ "contacts": [ {"id": "c200", "name": "Ravi Tamada" },
{ "id": "c201", "name": "Johnny Depp" }
]
}
another start with JSON array-
[{"appeId":"1","survId":"1"},
{"appeId":"2","survId":"32"}
]
Now how am i going to give a condition for them whether to know its a JSON array or Object? JSON array are object that i know but cant find how to separate them. i have tried the below:
JSONObject jsonObj = new JSONObject(jsonStr1);
if(jsonObj instanceof JSONArray){}
but if condition is showing error- incompatible conditional operand types JSONObject and JSONArray
You can simply use startsWith for String to check where the String starts with { or [
boolean isJsonArray = jsonResponse.startsWith("[");
if(isJsonArray){
// Its a json array
}
else{
// Its a json object
}
You can use JSONTokener class for that, here is a sample code for that.
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject){
JSONObject result = new JSONObject(response);
}
else if (json instanceof JSONArray){
JSONArray resultArray = new JSONArray(response);
}
make jsonobject and call which place u want to calling
jsonobject = JSONfunctions
.getJSONfromURL("http://ampndesigntest.com/androidapi/CURRENTPROJECTDATA/textfiles/hotels");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// map.put("latlongitude", jsonobject.getString("latlongitude"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
You could use the method has(String) to check if the JSONObject contains or not the key contacts.
if(jsonOjbect.has("contacts") {
...
}
else {
...
}
I have an array of JSON objects on an SD card.
I get the file contents like this:
File yourFile = new File("/mnt/extSdCard/test.json");
FileInputStream stream = new FileInputStream(yourFile);
String jString = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
jString = Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
The structure is like this:
[{"name":"john"},{"name":"fred"},{"name":"sam"}]
and I want to be able to parse them to make a listView. In JavaScript I can get them as an AJAX request and then do
var people = JSON.parse(data.responseText);
and then loop through the array. But I am a complete novice at java - I have found example code that does each of those things separately but I can't put them all together. Any help much appreciated.
The problem is that the above JSON structure represents a JSONArray and not a JSONObject
JSON Syntax
So after getting your jstring just do this
JSONArray array = new JSONArray(jString);
for(int i=0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
String value = obj.getString("name");
}
If you have it as a string, you should be able to parse it to a JSONObject with something like this:
JSONObject jObj = null;
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i(TAG, "JSON Data Parsed: " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
I would also put the data (in your example) into an array, so it appears as something like:
{"names": [{"name": "john"},{"name": "fred"},{"name": "sam"}]}
And then to read your object again, you can put it into an array (or something else I guess) with something like this:
// create an empty list
ArrayList<String> l = new ArrayList<String>();
// pull the array with the key 'names'
JSONArray array = jObj.getJSONArray("names");
// loop through the new array
for(int i = 0; i < array.length(); i++){
// pull a value from the array based on the key 'name'
l.add(array.getJSONObject(i).getString("name"));
}
Hope at least some of this helps out (or at least points you in the correct direction). There are PLENTY of resources on here though, too.
EDIT:
Read up on JSON formatting. [] denotes array and {} denotes object, so you have an array of objects. That is why I recommended changing your format. If you are set on your format, either go with what Mr.Me posted for his answer, or just split your string at special characters and put them into an array that way.
Try this
String[] from = new String[] {"name"};
int[] to = new int[] { R.id.name};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
try
{
JSONArray names = new JSONArray(jsonString);
Log.i("MyList","Number of names " + names.length());
for (int j = 0; j < names.length(); j++)
{
JSONObject jsonObject = names.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", jsonObject.getString("name"));
fillMaps.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
}
SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);
Here mListView is your predefined ListView.
Feel free to share your doubts here, if any.
[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}