JSONException on trying to create JSONArray - java

Please advice why I'm getting an exception on trying to create a JSONArray instance?
String task = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'menuitem': [ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}] }}}";
try {
JSONObject tmp = new JSONObject(task);
js = tmp.getJSONArray("menuitem"); // exception fires here
} catch(JSONException e) {
e.printStackTrace();
}
Getting an exception
01-03 16:12:17.926: WARN/System.err(5999): org.json.JSONException: No value for menuitem

'menuitem' is not a child of tmp. Try this:
js = tmp.getJSONObject("menu").getJSONObject("popup").getJSONArray("menuitem");

For me it worked like this:
JSON file:
{
"response":
{
"results":
[
{
"value1":"1",
"value2":"2"
},
{
"value1":"1",
"value2":"2"
}
],
"status":
{
"code":"200",
"message":"Success"
}
}
}
Then:
JSONArray array = responseObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
// CREATE YOUR OBJECTS
}

Related

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

I am getting HTTP response string like below. I want subject_id and status string from response string

Response string is like this:
{
"images": [
{
"transaction": {
"status": "success",
"topLeftX": 325,
"topLeftY": 451,
"gallery_name": "Ironman",
"subject_id": "Tony",
"confidence": 0.99414,
"height": 630,
"width": 630,
"face_id": 1,
"quality": 1.75477
},
"candidates": [
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644861022"
},
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644876280"
}
]
}
]
}
I tried this code but not working..
JSONArray arr = new JSONArray(response);
JSONObject jObj = arr.getJSONObject(0);
String status = jObj.getString("status");
String message = jObj.getString("subject_id");
Use json simple lib
JSONObject json = new JSONObject(yourString);
JSONArray images = json.getJSONArray("images");
and you can loop throw this array
for (int i = 0; i < images.length(); i++) {
JSONObject o = images.getJSONObject(i);
....
}
You can use GSON to parse JSON Strings. If you just want the first object of the images array you can use this code:
JsonParser jsonParser = new JsonParser();
JsonObject obj = jsonParser.parse(responseString).getAsJsonObject();
JsonArray images = obj.getAsJsonArray("images");
String subjectId = images.get(0).getAsJsonObject().get("transaction")
.getAsJsonObject().get("subject_id").getAsString();
You can create pojo class for response
Also you can use GSON library for get response string.
use this
#Override
protected void onPostExecute(String result) {
JSONObject jsonobj;
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
if (result.equals("failure")) {
Toast.makeText(context, "Check your Username or Password", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString()); JSONArray array = jsonobj.getJSONArray("images");for (int i = 0; i < array.length(); i++) {
JSONArray transaction = array.getJSONObject(i).getJSONArray("transaction");for (int i = 0; i < array.length(); i++)
String status = transaction.getJSONObject(i).getString("status");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
dialog.dismiss();
Toast.makeText(context, "Check net connection", Toast.LENGTH_LONG).show();
}
}
You tried
JSONArray arr = new JSONArray(response);
but you should
JSONObject arr = new JSONObject(response);
Because your main json is json object, not JSONArray

Parsing JSON array inside json array in android

I'm getting json from server like in this pattern.
[
{
"Response":[
{
"CategoryID":1,
"CategoryName":"Software",
"Count":1,
"Tasks":[
{
"ATId":17,
"TaskName":"Def",
"TaskId":17,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":2,
"CategoryName":"Hardware",
"Count":5,
"Tasks":[
{
"ATId":3,
"TaskName":"Def",
"TaskId":5,
"TaskDetails":"FGH"
},
{
"ATId":4,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":6,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":11,
"TaskName":"Def",
"TaskId":13,
"TaskDetails":"FGH"
},
{
"ATId":12,
"TaskName":"Def",
"TaskId":14,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":3,
"CategoryName":"Web",
"Count":1,
"Tasks":[
{
"ATId":13,
"TaskName":"Def",
"TaskId":11,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":4,
"CategoryName":"Ios",
"Count":3,
"Tasks":[
{
"ATId":5,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":8,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":15,
"TaskName":"Def",
"TaskId":15,
"TaskDetails":"FGH"
}
]
}
],
"MessageStatus":"Success",
"MessageCode":1
}
]
here I have array of objects which have inner objects also. So I tried to do it and fetched all the data but this is not in a form as i receive from server. All I need is to get a pattern in which i correctly get it. My java code is here.
#Override
public void onResponse(String response) {
ParentItems entryObj = null;
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonArr = new JSONArray(response);
// JSONArray js=jsonObj.getJSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
String code = null;
String Message = null;
try {
jsonObj = jsonArr.getJSONObject(0);
code = jsonObj.optString("MessageCode");
Message = jsonObj.optString("MessageStatus");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("1")) {
try {
Utilities.parentItemsList = new ArrayList < > ();
Utilities.childItemsList = new ArrayList < > ();
JSONArray array = jsonObj.getJSONArray("Response");
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
}
}
}
} else {
Toast.makeText(getContext(), "business ID is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
i need my show show data in a expandable listview in a pattern that Catagory object will be parent item and task will be child item
In your ParentItems class. Add another attribute like this:
class ParentItems {
...Other attributes
List<ChildItems> childItems;
}
Then in your parser do something like this:
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
entryObj.childItems = new ArrayList<>();
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
entryObj.childItems.add(childItems);
}
Utilities.parentItemsList.add(entryObj);
}
This way you will get all the children tasks as part of the parent object.
PS. For tasks like this, it's easier to use a library like GSON.
You have to make Two Model Class For This like below.
public class ParentItems{
String CategoryID;
String CategoryName;
String Count;
ArrayList<ChildItems> ChildList;
// Here Constuctor and Getter Setter
}
public class ChildItems{
String ATId;
String TaskName;
String TaskId;
String TaskDetails;
// Here Constuctor and Getter Setter
}
you have to add data like this
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
if(taskArray.length()>0){
ArrayList<ChildItems> list=new ArrayList<>();
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
list.add(childItems);
}
entryObj.setChildList(list);
}
}
For More see this link its help you. Expandable Listview Example

Read JSON Object from an Array using Simple JSON Jar

I have a JSON file as below
{
"ClassId": "1",
"ClassName": "mobiles",
"ClassItems": [
{
"ItemId": "1",
"ItemName": "Nokia",
"ItemImageName": "nokia.jpg",
"ItemUnitPrice": "200.00",
"ItemDiscountPercent": "0"
},
{
"ItemId": "2",
"ItemName": "Samsung",
"ItemImageName": "samsung.jpg",
"ItemUnitPrice": "400.00",
"ItemDiscountPercent": "0"
}
]
}
I am trying to access the ItemIds for all the items with ClassId=1. I am able to print the complete json array but I am not able to find print itemIds alone.
The java code I use is below:
public class JSONExample {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
JSONParser parser=new JSONParser();
try {
Object obj=parser.parse(new FileReader("JSON/TestJson.json"));
JSONObject jsonObject=(JSONObject) obj;
String classId=(String) jsonObject.get("ClassId");
String className=(String) jsonObject.get("ClassName");
if(classId.equals("1")){
JSONArray itemList = (JSONArray) jsonObject.get( "ClassItems" );
Iterator iterator=itemList.iterator();
while(iterator.hasNext())
{
System.out.println(itemList.get(1));
iterator.next();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
String itemId;
for (int i = 0; i < itemList.length(); i++) {
JSONObject obj= itemList.getJSONObject(i);
itemId=(String) jsonObject.get("ItemId");
}
Try the above instead of iterator.
Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

How to loop through json data in android

As mentioned in the title. How can I loop through my json data that I am getting from server. My getting this kind of json data
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Saleem",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
here is where I am getting my json data
public class Home extends Activity {
Button btnLogout;
ScrollView svHome;
UserFunctions userFunctions;
LoginActivity userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userid = new LoginActivity();
svHome = (ScrollView)findViewById(R.id.svHome);
setContentView(R.layout.home);
userFunctions = new UserFunctions();
/***********************************************************/
//here is where my above mentioned json data is
JSONObject json = userFunctions.homeData();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
//currently this only shows the first json object
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*******************************************************/
}
}
Update
After make changes accroding to the link given in the answer. Here are my changes
/***********************************************************/
JSONObject json = userFunctions.homeData();
String jsonData = json.toString();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("Object", jsonObject.getString("places"));
//Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please look over the link
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
an if possible made the changes in json, as there is no array braces "[" "]" in json and you need that to itrate in loop
json should be like that
{
"arrayKey": [
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
},
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
}
]
}
You could use the json libraries like the following:
import org.json.JSONArray;
import org.json.JSONObject;
which allows you to read json data into array like this:
JSONArray jsonArray = new JSONArray([your json data]);
Try this tutorial: http://www.vogella.com/articles/AndroidJSON/article.html
one other way I'll recommend is Use GSON library, It is easy end pain less. for well formatted Json
As your logcat states, you're trying to convert a JSONObject to a JSONArray:
org.json.JSONException: Value {"uid":"4fc8f94f1a51c5.32653037","places":{"place_photo":"http://example.info/android/places_photos/place1.jpg","created_at":"2012-06-02 00:00:00","seeked":"0","longitude":"24.943514","latitude":"60.167112"},"error":0,"success":1,"tag":"home","profile_photo":"http://example.info/android/profile_photos/profile1.jpg","name":"Zafar Saleem"} of type org.json.JSONObject cannot be converted to JSONArray
Try to debug the code - find out where the exception is thrown, and make a JSONObject there instead of a JSONArray.

Categories