I want to parse below JSON format,
Can anybody please advise a way to do it? Thanks.
JSON format, I want to parse
{
"questions": [
{
"question": "What is the scientific name of a butterfly?",
"answers": [
"Apis",
"Coleoptera",
"Formicidae",
"Rhopalocera"
],
"correctIndex": 3
},
{
"question": "How hot is the surface of the sun?",
"answers": [
"1,233 K",
"5,778 K",
"12,130 K",
"101,300 K"
],
"correctIndex": 1
},
{
"question": "Who are the actors in The Internship?",
"answers": [
"Ben Stiller, Jonah Hill",
"Courteney Cox, Matt LeBlanc",
"Kaley Cuoco, Jim Parsons",
"Vince Vaughn, Owen Wilson"
],
"correctIndex": 3
}
]
}
I am trying to get it done by the below codes, It's not completed, I can parse the first array and object inside it.
public List getGeneralQuestion(final AnswerListAsyncResponse callBack){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
URL, null, response -> {
try {
JSONArray jsonArray = response.getJSONArray("questions");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String question = jsonObject.getString("question");
int correctAnswer = jsonObject.getInt("correctIndex");
GeneralQuestions generalQuestions = new GeneralQuestions(question, correctAnswer);
generalQuestionsArrayList.add(generalQuestions);
JSONArray jsonAnsArray = jsonObject.getJSONArray("answers");
for (int j = 0; j < jsonAnsArray.length(); j++){
JSONArray jsonArrayList = jsonAnsArray.getJSONArray(j);
String answerList = jsonArrayList.getString();///////
GeneralQuestions generalAnswer = new GeneralQuestions(answerList);
generalAnsArrayList.add(generalAnswer);
}
}
Create your response model class. You can do it with an online tool or android studio plugins.
You can find a good online tool here .And about android studio plugins , Go to File -> Settings -> Plugins and search for JSON to POJO and install a good plugin and restart android studio in order to use it .
stop going through each and every JSON node since this is a simple JSON response. Use GSON for easy conversions. add GSON dependency to your app level Build.gradle file and start using GSON to convert your JSON response to a List of model class objects. It's simple and easy. You can find a good tutorial here.
Related
So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code
1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");
I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.
im trying to get data from the site which have mongodb as their database and CI ,i make simple script to make json encode output from the site and the output is like :
{
"mko680": {
"_id": {
"$id": "515be1807bfb8b1d0d000000"
},
"channel": [
"channel a",
"subchannel a"
],
"channel_id": 227,
"id": "mko680",
},
"mkv002": {
"_id": {
"$id": "515b32407bfb8b1d0d000000"
},
"channel": [
"channel a",
"subchannel b"
],
"channel_id": 232,
"id": "mkv002",
}
}
i try to parse that output in my android project like this
JSONArray obj = new JSONArray(outputlike o);
for (int i = 0; i < obj.length(); i++) {
JSONObject json_data = obj.getJSONObject(i);
Log.i("test",json_data.getString("channel_id"));
}
the logcat said org.JSON.Mismatch
any clue for which is json/my code that not right ?
thanks , and sory for my bad question hope you understand
UPDATED :
now i change it to json object like :
JSONObject arr = new JSONObject(bufstring);
for (int i = 0; i < arr.length(); i++) {
Log.i("test",arr.getString("channel_id"));
}
but the logcat now said , no value for channel_id, but it sure there is channel_id in that output, any clue ?
The data you receive is of the type JSONObject and not JSONArray. Therefore, you need to parse your json data like this:-
String jsonStr = "..."; //Your JSONString
JSONObject obj = new JSONObject(jsonStr);
JSONObject mkObj = obj.getJSONObject("mko680");
String channelId = mkObj.getString("channel_id");
Your return data is Jsonobject not an JsonArray.
So, you can create JsonObject,
JSONObject obj = new JSONObject(outputlike o);
thank all based on your answer i have figured it out, at first i got difficult to get dynamic key for getting the right object i use below code to solved it, dont think its the good one but i use this in temporary
JSONObject arr = new JSONObject(bufstring);
Iterator keys = arr.keys();
while(keys.hasNext()) {
String ambilKey = (String)keys.next();
JSONObject AmbilObject = arr.getJSONObject(ambilKey);
Log.i("test",AmbilObject.toString());
}
thanks for all suggestion, you're rock :D
I have a JSON as shown below:
{
"places": [{
"name": "Ankola",
"slug": "ankola",
"category": "beach",
"distance": "521",
"travel_time": "8 hrs, 2 mins",
"days": "3",
"latitude": "14.669456",
"longitude": "74.300952",
"weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
"todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
"about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}]
}
I know how to fetch key - value pairs, but i dont know how to parse array inside json to form a string array(image - in my case)
To summarize i want something like this:
I have 5 image names under "image" tag, i want them in a string array. How can i do this?
Use :
JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
String image = images.getString(i);
}
This should do the trick as I remember.
Here you go:
JSONArray ja = whatEverYourJsonObject.getJSONArray("image");
for(int i=0; i<ja.length(); j++){
String name = ja.getString(i);
}
You first have to convert the JSON string to a Java object (JSONObject). Then, you obtain your JSONArray and iterate over it.
Example:
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject (jsonString);
JSONArray images = itemObj.getJSONArray ("images");
int length = images.length ();
for (int i = 0; i < length; i++)
Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: Now I see that your JSON is invalid - you have an object for each image and that object contains only the value part of the data. An example of a valid images array would be as follows:
{
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}
I would suggest:
Create your own class which describes your data structure defined
by those json object. As a last resort you can even generate Java
class based on JSON string - look at
jsongen
When you will have your own Java class (let's say MyClass) you can easily parse JSON to your generated Java class using GSON, like:
MyClass myClass = gson.fromJson(jsonString, MyClass.class);