Call single object from Json file - java

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

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

android JSONException index 1 out of range [0..1] (Parse 2 json arrays inside 1 loop)

I have code like this, the value of jArrAnswer is
[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}]
the result from jArrAnswer.length() is 4
but why I got error
org.json.JSONException: Index 1 out of range [0..1).
try {
JSONArray jArrAnswerid = new JSONArray(answerid);
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i);
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswerid.getString("answerid");
String ans= jObjAnswer.getString("answer");
GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid);
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.
Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().
Print the jArrAnswerid.size() and check.
Try this
try {
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswer.getString("answerid");
String ans= jObjAnswer.getString("answer");
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
provided "answer" is your json array response
Try
String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String answerId = jsonObject.getString("answerid");
String answer = jsonObject.getString("answer");
//Use answerId and answer
}
}
} catch(JSONException e) {
e.printStackTrace();
}

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

Parsing JSON Not Showing out of range

I'm working on parsing JSON file in my java and the JSON file goes like this
{"System":[{"System1":{"DisplayName":"fabcd","InternalName":"AD","SystemCode":"0001","SystemName":"vnid"},"System2":{"DisplayName":"akdfkajfl","InternalName":"AD","SystemCode":"0001","SystemName":"kjdfkafdk"}}]}
I cannot access the all objects inside "System" array. Please help me on this. My code is this
Systems = jObj.getJSONArray("System");
Log.d("Array", Systems.toString());
JSONObject first = Systems.getJSONObject(0);
Log.d("CSystems",first.toString());
// looping through All Contacts
for(int i = 0; i <=Systems.length(); i++){
JSONObject c = Systems.getJSONObject(i);
Log.d("SubSystems", Systems.getString(0));
}
Thanks.
Shouldn't for loop be looping over first instead of Systems? (With changes to account for the fact it's an object, not an array.)
To parse
try
{
JSONObject jObj = new JSONObject("My Json string");
JSONArray jr = jObj.getJSONArray("System");
JSONObject jb= jr.getJSONObject(0);
JSONObject system1 = jb.getJSONObject("System1");
String name = system1.getString("DisplayName");
String internalname = system1.getString("InternalName");
String SystemCode = system1.getString("SystemCode");
String SystemName = system1.getString("SystemName");
JSONObject system2 = jb.getJSONObject("System2");
String name1= system2.getString("DisplayName");
String internalname1 = system2.getString("InternalName");
String SystemCode1 = system2.getString("SystemCode");
String SystemName1 = system2.getString("SystemName");
Log.i("..........",name+"..."+internalname+"..."+SystemCode+"..."+SystemName);
Log.i("..........",name1+"..."+internalname1+"..."+SystemCode1+"..."+SystemName1);
}catch(Exception e)
{
e.printStackTrace();
}
or
Same as above.
try
{
JSONObject jObj = new JSONObject("My json string");
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
for(int j = 1;j<3; j++){
JSONObject jb = c.getJSONObject("System"+(j));
Log.i("SubSystems", jb.getString("DisplayName"));
Log.i("SubSystems", jb.getString("InternalName"));
Log.i("SubSystems", jb.getString("SystemCode"));
Log.i("SubSystems", jb.getString("SystemName"));
}
}
}catch(Exception e)
{
e.printStackTrace();
}
or change your json to
{
"System": [
{
"DisplayName": "fabcd",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "vnid"
},
{
"DisplayName": "akdfkajfl",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "kjdfkafdk"
}
]
}
To parse. Changing json to above parsing is much more easier.
try
{
JSONObject jObj = new JSONObject("My json string);
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
Log.i("SubSystems", c.getString("DisplayName"));
Log.i("SubSystems", c.getString("InternalName"));
Log.i("SubSystems", c.getString("SystemCode"));
Log.i("SubSystems", c.getString("SystemName"));
}
}catch(Exception e)
{
e.printStackTrace();
}
You can also look at https://code.google.com/p/google-gson/

Categories