JSON can't read, key reading fail maybe - android

I wonder why I can't read the JSON Object like this :
{
"1":{"bulan":"Januari","tahun":"2012","tagihan":"205000","status":"Lunas"},
"2":{"bulan":"Februari","tahun":"2012","tagihan":"180000","status":"Lunas"},
"3":{"bulan":"Maret","tahun":"2012","tagihan":"120000","status":"Lunas"},
"4":{"bulan":"April","tahun":"2012","tagihan":"230000","status":"Lunas"},
"5":{"bulan":"Mei","tahun":"2012","tagihan":"160000","status":"Lunas"},
"6":{"bulan":"Juni","tahun":"2012","tagihan":"150000","status":"Belum Lunas"},
"panjang":6
}
with my android code like this :
try {
int length = jobj.getInt("panjang");
for(int n = 0; n < length; n++){
String m = Integer.toString(n)
JSONObject row = jobj.getJSONObject(m);
String bulan = row.getString("bulan");
String tahun = row.getString("tahun");
String tagihan = row.getString("tagihan");
String status = row.getString("status");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bulan", bulan);
map.put("tahun", tahun);
map.put("tagihan", tagihan);
map.put("status", status);
list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
It always return nothing, but it works fine if I change the key m to specific key like if
String m = "1";
and I can't use
JSONObject row = jobj.getJSONObject(n);
because getJSONObject() just accept string, not int.
is there something wrong with my code?

Your problem lies in the initial iterator value. It failed to search for key "0", because you don't have "0". Change it to:
for(int n = 1; n <= length; n++){
Should fix the problem.

Related

Why I am getting null JSON response?

I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...

Not able to convert data in JSON format android

I have some data which I want to convert into json object. The data I want is like
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
The weekday is of array type and others are json object type. I have done some code to convert it but I am able to convert it like
{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
Code for this :
Code for creating weekdata array :
String firstDay = etDate1.getText().toString() + "##" + etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" + etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
Conversion into json to send it into volley :
HashMap<String, String> params = new HashMap<String, String>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata.toString() );
JSONObject obj = new JSONObject(params);
And I get data like :
{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
How can I convert it like below format:
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
Please help.
This is happening because you have defined your Map as Map and converting your list to String using toString() method. Which is generating your String with . You should define your Map as Map and don't use the toString method while putting it into the Map.
Code:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata);
JSONObject obj = new JSONObject(params);
One question here is why are you using Map? is there is any special reason for that?
You can create JSON directly from JSONObject.
Sample Code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
With JSONObject you don't have to worry about generics.
As per your question,
How can I convert it like below format:
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
String firstDay = etDate1.getText().toString() + "##" +
etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" +
etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
JsonArray weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
After this wrap this in the JsonObject
JsonObject jsonObject = new JsonObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
Log.e("jsonResult",jsonObject.toString());
Try this and let me know #mishti.

JSONArray weird Output on Different Devices

hi i have the following String
[{"SUBSCRIBERID":"151-52-049","LONG":"46.69127274","LAT":"24.70912743"},{"SUBSCRIBERID":"151-29-016","LONG":46.69570000","LAT":"24.70770000"}]
i am converting this String to JSONArray
JSONArray jsonArrr = new JSONArray(String);
then looping the Array And getting JSONObject
for (int h = 0; h < jsonArrr.length(); h++) {
jsonObj = jsonArrr.getJSONObject(h);
Iterator<String> iter = jsonObj.keys();
Object valuee = "";
String key = iter.next();
Log.e(TAG, "key is: " + key);
try {
valuee = jsonObj.get(key);
Log.e(TAG, "key: " + key + "---value: " + valuee); //on htc key is SUBSCRIBERID and its value while on samsung key is LONG and its valuee!!
} catch (JSONException e) {
Log.e(TAG,"SOME ERROR: "+e);
}
in this for loop the value retrieved is the first value in each object.
on my HTC mobile the first value is displaying correctly as the value of SUBSCRIBERID buy on a samsung device, the first value is displaying as LONG.
please any help would be appreciated!!
Order of the keys is not defined. So if you execute the code on different devices you may see keys in different orders. REF
Returns an iterator of the String names in this object. The returned iterator supports remove, which will remove the corresponding mapping from this object. If this object is modified after the iterator is returned, the iterator's behavior is undefined. The order of the keys is undefined.
Use without Iterator as mentioned in comments and above answer
for (int h = 0; h < jsonArrr.length(); h++) {
jsonObj = jsonArrr.getJSONObject(h);
// Iterator<String> iter = jsonObj.keys();
// Object valuee = "";
// String key = iter.next();
// Log.e(TAG, "key is: " + key);
// try {
// valuee = jsonObj.get(key);
// Log.e(TAG, "key: " + key + "---value: " + valuee); //on htc key is SUBSCRIBERID and its value while on samsung key is LONG and its valuee!!
// } catch (JSONException e) {
// Log.e(TAG,"SOME ERROR: "+e);
// }
// use this code
String value = jsonObj.getString("SUBSCRIBERID");
Long lat = jsonObj.getLong("LAT");
Long long = jsonObj.getLong("LONG");
Log.d("json","subscribed:"+value+",lat"+lat+",long:"+long);
for (int h = 0; h < jsonArrr.length(); h++)
{
Log.e(TAG,"JSONObjet at "+h+" : "+jsonArrr.get(h).toString());
}
try to run this

How to Fetch Records from JSON Having the Same Name into Android's java file

[{"UserID":"vishi"},{"UserID":"vish"}]
this is the json data that I am sending from php...
how can i get these values with same name in android
Thanks,
JSONArray array = new JSONArray(...);
int length = array.length() ;
for (int i = 0; i < length; i++) {
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
}
[
{
"UserID": "vishi" // key is UserId. value is vishi
},
{
"UserID": "vish"
}
]
The key UserID is the same. Just loop through the array and get the value
ArrayList<String> list = new ArrayList<String>();
JSONArray jr = new JSONArray("your json");
for(int i=0i<jr.length();i++)
{
JSONObject jb = jr.getJSONObject(i);
String value= jb.getString("UserID");
list.add(value);
}
Note:
Blackbelt's answer will also work and it also has null check cause optJSONObject() could return null also. This is a better way
Drawing from blackbelt's answer
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
From the docs
public JSONObject optJSONObject (String name)
Added in API level 1
Returns the value mapped by name if it exists and is a JSONObject. Returns null otherwise.

data from a jsonobject in android

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.

Categories

Resources