I've got an Android app in which I get some JSON from an API, which I now need to decode. I'm pretty far, but I'm failing at getting the contents. The JSON I'm receiving looks like this:
{ "messages": [
{
"created": "1391783287",
"id": 1,
"is_supporter": false,
"text": "Behold! This is a message?"
},
{
"created": "1391783287",
"id": 3,
"is_supporter": true,
"text": "Behave! This is an answer!"
}
]}
And I've got this code:
#Override
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
And on the last line of the code above I get an error saying Error: org.json.JSONException: Value {"messages":[{"id":1,"created":"1391788514","text":"How do I pay to an IBAN?","is_supporter":false},{"id":3,"created":"1391788514","text":"What is a payment pool?","is_supporter":false}]} of type org.json.JSONObject cannot be converted to JSONArray
Does anybody have any idea whats wrong here or how I can solve this?
Your String is a JSON object containing a JSON array, try this :
JSONObject myJSON = new JSONObject(result);
JSONArray jArray = myJSON.getJSONArray("messages");
then iterate through your JSONArray ...
int size = jArray.length();
for (int i=0 ; i<size ; i++){
JSONObject itemInArray = jArray.get(i);
// get values inside the object, for example :
String text = itemInArray.getString("text");
}
You can use old http://www.json.org lib in your Java :
First read your json file content into String;
Then parse it into JSONObject, If there is array, then get the array;
JSONObject myJson = new JSONObject(myJsonString);
// get the JsonArray
JSONArray jArray = jobj.getJSONArray("messages");
//Loop through the array to get the JSONObjects
for(int i=0;i<jArray.length();i++) {
// use myJson as needed, for example
int id = jArray.getJsonobject(i).getString("id");
// etc
}
you are JSONArray is in inside the JSONObject
Do like this to get the data
#Override
protected void onPostExecute(String result) {
try {
JSONObject jobj = new JSONObject(result);
JSONArray jArray = jobj.getJSONArray("messages");
for(int i=0;i<jArray.length();i++) {
String created=jArray.getJsonobject(i).getString("created");
}
}
Related
I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}
I am using this code
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
bookItems bookItem = new bookItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
JSONObject bookChapter = jsonObject.getJSONObject("chapter");
bookItem.setbook_subtitle(bookChapter.getString("subtitle"));
JSONObject chapVerses = jsonObject.getJSONObject("verses");
JSONArray verseReaders = chapVerses.getJSONArray("readers");
JSONObject readersNum = verseReaders.getJSONObject("number");
verseReadNum = readersNum;
} catch (JSONException w) {
w.printStackTrace();
}
mbookItemsList.add(bookItem);
}
}
to parse this json.
[
{
"chapter": {
"subtitle": "Something happened in this in this chapter"
},
"verses": {
"about": [
{
"In this verse, a lot of things happened yes a lot!"
}
],
"readers": [
{
"read": false,
"number": "No body has read this verse yet"
}
],
}
},
...]
I am getting the "subtitle" correctly but I am having didfficulty getting "number".
From line JSONObject readersNum = verseReaders.getJSONObject("number"); Android studio is complaining that getJSONOBJECT (int) in JSONArray cannnot be applied to (java.lang.String)
Please, how do I properly parse this?
verseReaders is a JSONArray, so you need to iterate over (or take the first) JSONObject and then get the string from that object.
String readersNum = verseReaders.getJSONObject(0).getString("number");
You have to use nested loops. Just add one more for for "readers".
This is my JSON
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
Now I am trying to display it into a listView how would I do that this is what i have right now (for testing purposes i am just trying to display all the names in a toast)
JSONObject jsonObj = new JSONObject(jsonStr);
int length = jsonObj .length();
for(int i=0; i<length; i++) {
Toast.makeText(this, jsonObj.getJSONArray("data").
getJSONObject(i).getString("Name"), Toast.LENGTH_LONG).show();
}
The Above code only display one name and not multiple names. How can I make it for multiple names?
Take a look this code snippet
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name").toString(), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name").toString(), Toast.LENGTH_LONG).show();
}
}
I recommend to use 'Log' instead using 'Toast'.
If any confusion or query let me know, i will try my best to resolve it.
If answer is satisfiable please mark it as correct answer.
Happy coding!
Thanks
You are getting the length of JSONObject, but you should get the length of JSONArray inside that JSONObject in order to iterate though json array items.
int length = jsonObj.getJSONArray("data").size()
I think you are guessing it wrong. Look closely you have a Json in that you have array which is JsonArray with the name/key "data"
then in that you can get it and traverse it index by index. For you I am providing you a road map so that things make easy for you conceptually
Make a model class which may able to store the values as you are getting in response of your api or in this json respone.
Take an array of type of your model class to store values
Now you can add for loop to save values or you can parse and save your jason array into your array you made to handle the jasonarray
this is easily be understand by this link and this is a working example to parse the json array and to show in your list view. You have nothing to worry about after reading these two links.
get your result from URL where your json is and store to any variable (result here) , then decode it i am showing below,
try this , it may give you some hint , i have not tried but may help you
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.optJSONArray("data");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
int id = jsonObjects.optInt("id");
String varMessage = jsonObjects.optString("varMessage");
String Image = jsonObjects.optString("Image");
String Category = jsonObjects.optString("Category");
String Method = jsonObjects.optString("Method");
JSONArray jsonArrayIngredients = jsonObject.optJSONArray("Ingredients");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String name = jsonObjects.optString("name");
}
}
}
I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.
I am getting the following exception.
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject
I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?
Below is the java code.
JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
Below is the json file content.
[
{
"friends": [
{
"id": 0,
"name": "test1"
},
{
"id": 1,
"name": "test2"
}
]
}
]
Your JSON contains an array which has one single object element so you should parse it like that:
JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
If it can have more elements add a for loop instead of root.get(0).
I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}
Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);
JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.