I am working on parsing data from a JSON url.
But the JSONobjects have different keys.
I want to get all the data from each json object and when it doesn't have that key I want to give it a default message.
This is what I'm trying to use:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
I got this variable
private static final String TAG_ABV = "abv";
I tried doing this to check if the abv key was included in the JSON and give the string a default text of "No value" when it was not inculed.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
But I have this error: cannot find symbol variable abv
I guess the abv inside the if statement is out the scope.
You're declaring abv inside the if/else blocks, which means it's only accessible inside that block. When you try to use it later (in data.put(TAG_ABV, abv); the variable you created is no longer accessible - it's out of scope. If you move the declaration of abv to the line before the if/else statement, that should fix your error.
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 am trying to parse a json response in android for my android application. I am getting org.json.JSONException. The response is as shown below:
{
id: "12345"
email:"abc#gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
I am trying to parse the response as shown below:
if (response != null) {
try {
//JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray contacts = new JSONArray(response.toString());
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
id = c.getString("_id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Can any one let me know what mistake am I doing in parsing the response. All suggestions are welcome.
Simply replace this you are using "_id" instead of "id"
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
Change this id = c.getString("_id"); to id = c.getString("id");
in the future, you may show error in logcat when parsing like this:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
There are two things I can think of , first of all you should get to know that what are [] , {} . The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong
1>
JSONArray contacts = new JSONArray(response.toString()); "this is culprit"
You should change it to
JSONObject. Use JSONObject in place of JSONArray
and Secondly
2> change this key id = c.getString("_id");to
id = c.getString("id");
Make sure You are getting and writing spellings of all keys right else it would generate exception.
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'm trying to take the information from the JSON returned by Google Places.
jsonObj = new JSONObject(data);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
System.out.println(result.getString("name"));
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
My question is, how can I make sure the either "name" or "reviews" are available to parse? that if (result.getJSONArray("reviews") != null) still fails because getJSONArray is empty.
You can do this by using the opt commands instead of the get commands. Change the get json array to the following:
(result.optJSONArray("reviews") != null)
Check out the JSONObject documentation for a complete list. You can also use the JSONObject has(String name) command to check if it exists before actually getting it.
Since your json is initially in the form of a JSONObject, you could use it's isNull(String name) helper method to check if a mapping exists and isn't null.
From the documentation:
isNull(String name) Returns true if this object has no mapping for
name or if it has a mapping whose value is NULL.
For example:
try {
jsonObj = new JSONObject(data);
if(!jsonObj.isNull("results")){
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
if(!result.isNull("name"){
System.out.println(result.getString("name"));
}
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
}
} catch(JSONException e){
//Something went wrong
}
The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.