[
{
"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 :)
Related
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.
I am learning how to implement Json in my project and have this Json file:
{
"stations":[
{
"station":"no1",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
}
]
}
I am able to succesfully display all values in a TextView, but I am only interested in lets say station no1. How do I pass the values from only station no1 in a textView?
This is my Json code:
try {
JSONObject jsonObject = new JSONObject(contents);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
} catch (JSONException e) {
e.printStackTrace();
}
Instead of using
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
You can do
JSONObject stations = jsonArray.getJSONObject(0);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
This way you will only get the values of the first element in your JSON.
Intead of using loop to all array length, get only first object details like below :
try {
JSONObject jsonObject = new JSONObject(contents);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
JSONObject stations = jsonArray.getJSONObject(0);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
} catch (JSONException e) {
e.printStackTrace();
}
This is my J-SON parsing i don't understand where i am making mistake . Anyone please look at the code and tell me what i am doing wrong.I also provided the J-SON URL
private Weather extractFeatureFromJSON (String json_incoming){
Weather sendInformation = null ;
try {
JSONArray jsonArray = new JSONArray(json_incoming);
JSONObject jsonObject = jsonArray.getJSONObject(0);
long timeReceived = jsonObject.getLong("EpochTime");
String weatherStatusReceived = jsonObject.getString("WeatherText");
boolean DayOrNightReceived = jsonObject.getBoolean("IsDayTime");
JSONObject fetchTemperature = new JSONObject("Temperature");
JSONObject dive_deep_t = fetchTemperature.getJSONObject("Metric");
double tempReceived = dive_deep_t.getDouble("Value");
JSONObject fetch_RF_Temperature = new JSONObject("RealFeelTemperature");
JSONObject dive_deep_t1 = fetch_RF_Temperature.getJSONObject("Metric");
double RF_tempReceived = dive_deep_t1.getDouble("Value");
JSONObject fetch_wind = new JSONObject("Wind");
JSONObject fetch_wind_direction = fetch_wind.getJSONObject("Direction");
int directionDegreeReceived = fetch_wind_direction.getInt("Degrees");
String in_which_direction = fetch_wind_direction.getString("Localized");
JSONObject fetch_wind_speed = fetch_wind.getJSONObject("Speed");
JSONObject fetch_wind_speed_in_metrics = fetch_wind_speed.getJSONObject("Metric");
double speedReceived = fetch_wind_speed_in_metrics.getDouble("Value");
int i = Integer.parseInt(in_which_direction);
int directionAndInWhich = directionDegreeReceived + i;
return new Weather(tempReceived , RF_tempReceived , DayOrNightReceived , weatherStatusReceived ,timeReceived , speedReceived , directionAndInWhich);
} catch (JSONException e) {
e.printStackTrace();
}
return null ;
}
http://dataservice.accuweather.com/currentconditions/v1/257072?apikey=JTgPZ8wN9VUy07GaOODeZfZ3sAM12irH&language=en-us&details=true
You need to getJSONObject from jsonObject instead of creating new JSONObject
To get Temperature, RealFeelTemperature, Wind Object you need to use
jsonObject.getJSONObject("Temperature");
jsonObject.getJSONObject("RealFeelTemperature");
jsonObject.getJSONObject("Wind");
Not new JSONObject
new JSONObject("Temperature");
new JSONObject("RealFeelTemperature");
new JSONObject("Wind");
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")
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?