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

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.

Related

Parse json in Java android studio

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

Call single object from Json file

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();
}

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 :)

Look at my JSON, my data is not showing in the UI

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");

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

Categories