How to read Json Android - java

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

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

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

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

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