PHP return Json String into JsOnObject fail - java

this is php return json string
<?php
date_default_timezone_set('Asia/Kuala_Lumpur');
$data = file_get_contents("php://input");
//echo $data;
//$obj = var_dump(json_decode($data));
$json = json_decode($data);
mysql_connect("localhost", "root", "123456") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");
if (is_object($json)) {
$d = array();
foreach($json->details as $obj) {
$Ticket_No = $obj->{'Ticket_No'};
$Ticket_Date = $obj->{'Ticket_Date'};
$Amount = $obj->{'Amount'};
$In_Out = $obj->{'In_Out'};
$Vehicle_ID = $obj->{'Vehicle_ID'};
$From_LocationID = $obj->{'From_LocationID'};
$PriceType_ID = $obj->{'PriceType_ID'};
$Trip_ID = $obj->{'Trip_ID'};
$To_LocationID = $obj->{'To_LocationID'};
$Inspector_Print = $obj->{'Inspector_Print'};
$Driver_ID = $obj->{'Driver_ID'};
$Updated_Time = date("Y-m-d H:i:s");
$Route_ID = $obj->{'Route_ID'};
//echo $_id;
$query = "INSERT INTO tbl_ticket (Ticket_No,Ticket_Date,Amount,In_Out,Vehicle_ID,From_LocationID,PriceType_ID,Trip_ID,To_LocationID,Inspector_Print,Driver_ID,Updated_Time,Route_ID)VALUES('".$Ticket_No."','".$Ticket_Date."','".$Amount."','".$In_Out."','".$Vehicle_ID."','".$From_LocationID."','".$PriceType_ID."','".$Trip_ID."','".$To_LocationID."','".$Inspector_Print."','".$Driver_ID."','".$Updated_Time."','".$Route_ID."')";
$rs = mysql_query($query) or die ("Error in query: $query " . mysql_error());
if ($rs) {
$d[] = array('Ticket_No' => $Ticket_No ,'Updated_Time' => $Updated_Time);
}
//break;
}
$pass_json = json_encode($d);
echo $pass_json;
}
?>
this is my json String
[{"Ticket_No":1950,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1951,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1952,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1953,"Updated_Time":"2014-03-01 02:15:02"}]
i m trying to put my json string in JsonObject, and put in a map, then use a map to get the every row Ticket_No value, but unfortunately failed, how to let me json string into Jsonobject or jsonarray and loop the row get the Ticket_No and Updated_Time ?
try {
JSONObject jsonObject = new JSONObject(jsonstring);
Iterator keys = jsonObject.keys();
Map<String, String> map = new HashMap<String, String>();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, jsonObject.getString(key));
}
System.out.println(map);
} catch (JSONException e) {
e.printStackTrace();
}
or
JSONArray jsonArray = new JSONArray(jsonstring);
JSONArray jsonPersonData = jsonArray.getJSONArray(1);
for (int i=0; i<jsonPersonData.length(); i++) {
JSONObject item = jsonPersonData.getJSONObject(i);
String Ticket_No = item.getString("Ticket_No");
Log.d(null,"Ticket_No= "+Ticket_No);
String Updated_Time = item.getString("Updated_Time");
}
also can't, why?

Because it's not complete JSON, try doing
{"tickets": [
{"Ticket_No":1950,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1951,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1952,"Updated_Time":"2014-03-01 02:15:02"},
{"Ticket_No":1953,"Updated_Time":"2014-03-01 02:15:02"}
]}
I would suggest at the end of the for loop do something like this
$return_json = array('tickets' => array($d));
$pass_json = json_encode($return_json);
echo $pass_json;

Related

I am not able to get the data from a Json array

Error message: com.example.myjson W/System.err: org.json.JSONException: Value
of type org.json.JSONObject cannot be converted to JSONArray
JSON is as follows
{
"temp":296.88,
"feels_like":298.86,
"temp_min":296.88,
"temp_max":296.88,
"pressure":1013,
"humidity":89,
"sea_level":1013,
"grnd_level":986
}
I could get data from this alone
String weatherInfo = jsonObject.getString("weather");
Not from this string Why ?
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
String weatherInfo1 = jsonObject.getString("main");
Log.i("weatherMainContent", weatherInfo1);
Log.i("Weather Details" , weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
Log.i("full " , jsonArray1.toString());
String message = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String main = jsonObject1.getString("main");
String description = jsonObject1.getString("description");
Log.i("Weather side Details" , weatherInfo);
Log.i("temperaturerrr", jsonObject1.getString("temp_min"));
String temp_min = jsonObject1.getString("temp_min");
Log.i("temperature", jsonObject1.getString("temp_min"));
String pressure = jsonObject1.getString("pressure");
if (!main.equals("") && !description.equals("") && !temp_min.equals("")) {
message += main + ":" + description +";" + temp_min + "\r\n";
} else {
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
Log.i("Main", jsonObject1.getString("main"));
Log.i("Description", jsonObject1.getString("temp_min"));
}
if (!message.equals("")) {
resultTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
}
}
Your Json is not an Array, but an Object.
Create a new JSONObject of your Json String.
Then just use the object and use the getDouble("propertyName") method to get the value of the property:
String json = "{\"temp\":296.88,\"feels_like\":298.86,\"temp_min\":296.88,\"temp_max\":296.88,\"pressure\":1013,\"humidity\":89,\"sea_level\":1013,\"grnd_level\":986}";
JSONObject weatherInfo = new JSONObject(json);
double temp = weatherInfo.getDouble("temp");
double feels_like = weatherInfo.getDouble("feels_like");
double temp_min = weatherInfo.getDouble("temp_min");
double temp_max = weatherInfo.getDouble("temp_max");
double pressure = weatherInfo.getDouble("pressure");
double humidity = weatherInfo.getDouble("humidity");
double sea_level = weatherInfo.getDouble("sea_level");
double grnd_level = weatherInfo.getDouble("grnd_level");
System.out.println(temp);
System.out.println(feels_like);
System.out.println(temp_min);
System.out.println(temp_max);
System.out.println(pressure);
System.out.println(humidity);
System.out.println(sea_level);
System.out.println(grnd_level);
If this is your data
"{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200} "
you have to just make some changes in the code to retrieve
String jsonString = "your string";
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("weather");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject weatherObj = jsonArray.getJSONObject(i);
System.out.println(weatherObj);
}
String baseValue = json.getString("base");
Object mainValue = json.get("main");
Object visibilityValue = json.get("visibility");
Object windValue = json.get("wind");
#shivas To retrieve the below json { "main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80} from the source json, kindly check first which property is JSONArray and JSONObject.
Here is the code to retrieve it.
main,wind are JSONObject and weather is a JSONArray.
So assuming sourcejson is the entire JSONObject,
JSONObject main = sourcejson.optJSONObject("main");
System.out.println(main.toString());
JSONObject wind = sourcejson.optJSONObject("wind");
System.out.println(wind.toString());
JSONArray weather = sourcejson.optJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
System.out.println(weatherObj.toString());
}
String base = sourcejson.optString("base");
int visibility = sourcejson.optInt("visibility");
Try this, you will get your data.

JSONObject has value but returns null value

[
{
"valve": "4679",
"selling": "5516",
"bal": "9075.4",
"o id": "37",
"invested": "11122", //<<<<<<<- this value returns null
"aProfit": "1012", //<<<<<<<- this value returns null
"count": "182", //<<<<<<<- this value returns null
"cost": "5051" //<<<<<<<- this value returns null
}
]
.- The JSONObject above requested from onPostExecute
#Override
protected void onPostExecute (String ANSWER)
{ String u_id;
try{
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); )
{
JSONObject JO = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
CASH = (String) jsonObject.getString("bal");
USER_VALUE = (String) jsonObject.getString("valve");
INVEST = (String) jsonObject.getString("invested");
PROFIT = (String) jsonObject.getString("aProfit");
COST_P = (String) jsonObject.getString("cost");
COUNT = (String) jsonObject.getString("count");
DashBoard.mprofit.setText(PROFIT);
DashBoard.minvest.setText(INVEST);
DashBoard.massets.setText(COST_P);
DashBoard.mvalue.setText(USER_VALUE); //<<<<<<<- this value returns the value.
Many others do, but some just refused to return and when I cross-check with postman, they all return.
so am now confused because if I swap the places of the valve and the count in the webservices code, it is no more null and vice versa.
Short question: can someone please explain why some values return null in the java coding.
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
//jsonObject = jsonArray.getJSONObject(i); **remove this line thne check remove this line thne check**
String CASH = (String) jsonObject.getString("bal");
String USER_VALUE = (String) jsonObject.getString("valve");
String INVEST = (String) jsonObject.getString("invested");
String PROFIT = (String) jsonObject.getString("aProfit");
String COST_P = (String) jsonObject.getString("cost");
String COUNT = (String) jsonObject.getString("count");
}
}catch (Exception e){
}
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
String CASH = (String) jsonObject.getString("bal");
String USER_VALUE = (String) jsonObject.getString("valve");
String INVEST = (String) jsonObject.getString("invested");
String PROFIT = (String) jsonObject.getString("aProfit");
String COST_P = (String) jsonObject.getString("cost");
String COUNT = (String) jsonObject.getString("count");
}
}catch (Exception e){
}
Try to use this code:
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
String valve = (String) jsonObject.getString("valve");
String selling = (String) jsonObject.getString("selling");
String bal = (String) jsonObject.getString("bal");
String o_id = (String) jsonObject.getString("o_id");
String invested = (String) jsonObject.getString("invested");
String aProfit = (String) jsonObject.getString("aProfit");
String count = (String) jsonObject.getString("count");
String cost = (String) jsonObject.getString("cost");
}
}catch (Exception e){
}
Hope this helps...
Happy Coding :)

my json parser for jsonarry just get the first element

i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")

How to read Json Android

i so confused ! i'm so trying to read this json but i can't :-(
here is my code :
{"status":"loged_in","token":"8e88776a14f4da4ef8e00955f83e1397","nikeName":"سعید"}
try {
postTextandGetRespons("http://gfac.ir/KatibehPayam/Service/login.php");
JSONArray messages = new JSONArray(responseString);
for ( int i=0; i<= messages.length();i++){
JSONObject c = messages.getJSONObject(i);
Status[0] = c.getString("status");
Status[1] = c.getString("token");
Status[2] = c.getString("nikeName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Your responseString contains an object not an array so use JSONObject instead of JSONArray
JSONObject message = new JSONObject(responseString);
String status = message.getString("status");
String token = message.getString("token");
String nikeName = message.getString("nikeName");

A JSONObject text must begin with '{' at 1

I am new to both JSON and JSP. I am writing a REST url, that will be called from a java swing application. the url will display some JSON data.
below is my jsp code:
JSONObject MainObject=null;
JSONObject json1=null;
JSONArray jarr=new JSONArray();
String email = request.getParameter("EMAIL");
cc = new MySQLConnection();
String query = "SELECT * FROM CLIENTS WHERE EMAIL = '"+email+"'";
try{
conn =cc.db();
stmtt =conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmtt.executeQuery(query);
if(rs.next()){
json1 = new JSONObject();
MainObject = new JSONObject();
json1.put("EMAIL", rs.getString("EMAIL"));
json1.put("ID", rs.getLong("ID"));
json1.put("COMPANY", rs.getString("COMPANY"));
json1.put("CODE", rs.getString("CODE"));
json1.put("VALID_TILL", rs.getLong("VALID_TILL"));
jarr.put(json1);
MainObject.put("SUCCESS", "1");
MainObject.put("CLIENTS", jarr);
}
//else{
//out.println("Error....");
//}
out.println(MainObject);
}
catch(SQLException ex){out.println(ex);}
finally{try{stmtt.close(); rs.close();conn.close();} catch(SQLException ex){out.println(ex);} }
This gives me the following output: {"SUCCESS":"1","CLIENTS":[{"VALID_TILL":20,"COMPANY":"BOOK PALACE","ID":1,"EMAIL":"pranjal","CODE":"98877655"}]}
Now when I try to parse the data from Swing application: it gives me error. I am parsing like this:
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("EMAIL", mail)) ;
JSONObject json = jParser.makeHttpRequest(YOURUrl, "GET", params);
System.out.println(json.toString());
try {
int success = json.getInt("SUCCESS");
if (success == 1) {
products = json.getJSONArray("CLIENTS");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String Company = c.getString("COMPANY");
String Name = c.getString("C_NAME");
String Email = c.getString("EMAIL");
String Code = c.getString("CODE");
String ValidTill = c.getString("VALID_TILL");
String sl = c.getString("ID");
COMPANY = Company;
CNAME = Name;
EMAIL = Email;
CODE = Code;
VALID_TILL = ValidTill;
SL = sl;
}
}
} catch (JSONException e) {
System.err.println(e);
}
What is the error in my jsp file? Where am I doing wrong?

Categories