Android JSON Parse - android

I have this json response:
[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]
I need to parse it on android.
I have trying follow code:
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("");
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));
But it doesnt work.
If my result will be:
{ "data":[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]}
And I modify the code in:
JSONArray jsonArray = obj.getJSONArray("data");
It works.
How Can I parse It considered my first json response (without "data")
Thank you.

You should use next code:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));
Because you have not an object in json, but an array, so you should create array instead of object. And thats why your modification works. Because in modified code "data" is an object (JSONObject)

JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
pic = row.getString("pic");
}
Or you can just use Gson Library. Just create your pojo classes
public class Data{
int id;
String cat;
String pic;
String sector;
//setter and getter
}
then,
List<Data> datas = gson.fromJson(string_of_json_array, new TypeToken<List<Data>>(){}.getType());
for(Data item: datas){
String pic = item.getPic();
}

Related

Problem with using JSON when trying get more data like "fields"

I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray

Difficult to identify json data

I have json data as mentioned below.
{
"data":[
{
"Products":{
"id":"86",
"pname":"mi4",
"pcat":"9",
"subcat":"8",
"seccat":"0",
"oproduct":"1",
"pdetails":"Good phone",
"pprice":"10000",
"pdiscount":"10",
"qty":"1",
"qtytype":"GM",
"dcharge":"40",
"pimage":null,
"sname":"Easydeal",
"sid":"1100",
"size":"",
"pincode":""
}
}
]
}
I can identify array as getJSONArray("datas"). But I want to get pname and sname values.
Just reach the object
JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");
now if you want to get object at a particular index(say '0')
JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");
you can similarly traverse the array
for(int i=0;i<data.lenght();i++){
JSONObject objAtI=data.getJSONObject(i);
JSONObject products=objAtI.getJSONObject("products");
String pName=products.getString("pname");
}
To get the to the key "Products" you should do:
JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");
Then to get the values in productsObject you should do:
productsObject.getString("id");
productsObject.getString("pdetails");
And so on.
Try out the following code:
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
This is how you get pname and sname:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
try {
jsonArray = jsonObject.getJSONArray("data");
for(int counter = 0; counter <jsonArray.length(); counter++){
JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
JSONObject products = jsonObject1.getJSONObject("Products");
String pname = products.getString("pname");
String sname = products.getString("sname");
}
} catch (JSONException e) {
e.printStackTrace();
}
PS: Poor JSON structure :)

Retrieving Data with JSON in Android

My application connects to the web and retrieves a JSON file. I am having some issues retrieving the data that I need from this file. Here is the link to the JSON file: http://api.wunderground.com/api/f9d9bc3cc3834375/forecast/q/CA/San_Francisco.json
Here is a snippet of what it looks like:
I would like to get the value of the "period" variable in the first JSon object within the "forecastday" array, which should be 0. Here is how i'm looking at this. "forecastday" is the array, within that there are a number of JSon objects, each containing variables like "period","icon"....."pop".
In my code, I attempt to get the JSON array "forecastday" and then get the first Json object of the array, I then retrieve the value of "period" in that object and set it in a TextView:
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray contacts = jsonObj.getJSONArray("forecastday");
JSONObject c = contacts.getJSONObject(0);
String period = c.getString("period");
responseView.setText(period);
} catch (JSONException e) {
e.printStackTrace();
}
}
When I run the code, nothing is being retrieved. I'm new to working with JSon and am wondering if I'm looking at this wrong. Please help.
Your "forecastday" JSONArray is inside the "txt_forecast" JSONObject that is inside the "forecast" JSONObject of your response, so you have to extract your JSONArray from this JSONObject and not from the root JSON response :
try {
JSONObject jsonObj = new JSONObject(response);
--> JSONObject forecatsObj = jsonObj.getJSONObject("forecast");
--> JSONObject txtForecatsObj = forecatsObj.getJSONObject("txt_forecast");
JSONArray contacts = txtForecatsObj.getJSONArray("forecastday");
...
You were close but it is incorrect, try like this:
JSONObject jsonObj = new JSONObject(response);
JSONObject forecast = jsonObj.getJSONObject("forecast");
JSONObject txtForecast = forecast.getJSONObject("txt_forecast");
JSONArray forecastDay = txtForecast.getJSONArray("forecastday");
//parse the first period value
String period = forecastDay.getJSONObject(0).getString("period");
responseView.setText(period);
Try this code :
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject forecastObj = jsonObj.getJSONObject("forecast");
JSONObject txt_forecastObj = forecastObj.getJSONObject("txt_forecast");
JSONArray foracastdayArray = txt_forecastObj.getJSONArray("foracastday");
JSONObject oOjb0 = foracastdayArray.getJSONObject(0);
String period = oOjb0.getString("perioed");
}catch (Exception e){
}
This code works for me fine:
JSONObject jsonResponse = new JSONObject(responce);
JSONArray jsonMainNode = jsonResponse.optJSONArray("forecastday");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String period = jsonChildNode.optString("period");
responceView.setText(period);
}

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

Problems with getting values from JSON object

I'm trying to get data once user logged in successfully but I never get any of results, what I am doing is next:
// response is my request to server
JSONObject obj = new JSONObject(response);
Log.d("RESPONSE",obj.toString());
so in log I do see values, like:
04-19 11:28:16.729: D/RESPONSE(3162): {"data":[{"loses":3,"username":"benedict","level":1,"strength":15,"experience":null,"gold":10,"password":"benedict","intelligence":5,"agility":10,"wins":5}],"status":true}
but once I try to read username for example like this:
String username = obj.getString("username");
The code above ^ gives me nothing in my string..
Any help how I can retrieve data from JSONObject? Thanks!
That is because the username is present in the data object, which happens to be an JSONArray. Get the data array from the response object, traverse through each JSONObject in the array, and from each object, extract your username.
Something like this:-
JSONObject obj = new JSONObject(response);
JSONArray data = obj.getJSONArray("data");
for(int i=0;i<data.length();i++){
JSONObject eachData = data.getJSONObject(i);
System.out.println("Username= "+ eachData.getString("username"));
}
your field username is in array data. To access into this try :
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
for(int i = 0; i < array.length(); ++i){
JSONObject data = array.getJSONObject(i);
String username = data.getString("username");
}
You need to first get JSONArray which is data :
JSONArray data = null;
data = json.getJSONArray("data");
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String username = c.getString("username");
}
You can get idea about parsing JSON from HERE
Try this...
try {
JSONObject object = new JSONObject(response);
JSONArray Jarray = object.getJSONArray("data");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
String loose= Jasonobject.getString("loses");
String username=Jasonobject.getString("username");
.......
........
}
} catch (JSONException e) {
Log.e("log_txt", "Error parsing data " + e.toString());
}

Categories

Resources