This is my JSonArray
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":[
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
]
}
and this is my java code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
JSONArray childrenProducts = jsono.getJSONArray("products");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.println("inside products");
System.out.print(jsonData.getString("name") + "<----dd");
}
The first for loop is working fine but the second forloop is not.. i dont get anything if i try to execute those print statements inside the second for loop.. please help me!!
Why don't you use Gson to get parse the JSON string simply?
You need to declares classes first to match the JSON response like this.
public class Vendor {
private String vendor_name;
private String vendor_description;
private String vendor_slug;
private String vendor_logo;
private String contact_number;
public Vendor() {
}
public String getVendor_name() {
return vendor_name;
}
public String getVendor_description() {
return vendor_description;
}
public String getVendor_slug() {
return vendor_slug;
}
public String getVendor_logo() {
return vendor_logo;
}
public String getContact_number() {
return contact_number;
}
}
...
public class Product {
private String name;
private String price;
private String image;
public Product() {
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getImage() {
return image;
}
}
Now declare the Response class like this
public class Response {
private List<Vendor> vendor;
private List<Product> products;
public Response() {
}
public List<Vendor> getVendor() {
return vendor;
}
public List<Product> getProducts() {
return products;
}
}
Now, once you've the JSON string its easy to bounce the data using GSON into the Response class like this.
Gson gson = new Gson();
Response mResponse = gson.fromJson(jsonString, Response.class);
Simple!
It is not going in your second for loop because there is SomeException in your first for loop.
Your execution will be thrown out to any catch() clause, and the further execution will not be done including your second for loop.
Just try putting that up like this:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
JSONArray childrenProducts = jsono.getJSONArray("products");
//this will be executed now..!!
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.println("inside products");
System.out.print(jsonData.getString("name") + "<----dd");
}
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
This is how i solved it:
try {
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsono = new JSONObject(response);
JSONArray childrenProducts = jsono.getJSONArray("products");
System.out.println(childrenProducts.length()+"LENGTH");
for(int i=0; i<childrenProducts.length(); i++){
JSONObject jsonData1 = childrenProducts.getJSONObject(i);
System.out.println(childrenProducts.length() + "LENGTH");
System.out.print(jsonData1.getString("name") + "<----dd");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
just had to take two separate try blocks... can someone please tell why was it not working in one try block? the above code works
Related
I am a beginner in the use of JSON.
So I try to extract the url of an image from a JSON reply.
Here is the code that allows me to get an Array:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
//String url ="http://www.google.com";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search&album="+albumName+"&api_key=c51f8eb36bad&format=json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
//mTextView.setText("Response is: "+ response.substring(0,500));
Log.i("RESPONSE","Response is: "+ response);
JSONObject jsono = new JSONObject();
try {
jsono = new JSONObject(response);
//String url = jsono.getString("results");
//Log.i("RESPONSE",url);
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
try {
jsonArray = jsono.getJSONObject("results").getJSONObject("albummatches").getJSONArray("album");
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
try {
object = jsonArray.getJSONObject(i);
Log.i("RESPONSE",object.getString("image"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("RESPONSE","That didn't work!");
}
});
queue.add(stringRequest);
And here is the structure of this part in the JSON answer:
{
"album": [
{
"name": "DD Y Ponle Play",
"artist": "Jumbo",
"id": "2528039",
"url": "http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play",
"image": [
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "small"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "medium"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "large"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "extralarge"
}
]
}
]
}
How to get the url of an image for a given size?
Thank you very much for your suggestions.
You can use google GSON for this. Import it as a dependency
First create an album class.
public class Albums {
private List<Album> album;
public List<Album> getAlbum() {
return album;
}
public class Album{
private String name;
private String artist;
private String id;
private String url;
public String getName() {
return name;
}
public String getArtist() {
return artist;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public List<Image> getImage() {
return image;
}
public class Image {
#SerializedName("#text")
private String text;
private String size;
public String getText() {
return text;
}
public String getSize() {
return size;
}
}
private List<Image> image;
}
}
Now in your code where you get the above JSON object try this code below
Gson gson = new Gson();
// Im assuming "response" as the above JSON object
Albums albums = gson.fromJson(response.optString("album"),Albums.class);
This will map your json to java object.(Note: You can remove unwanted objects from the POJO as you like)
You can get the image using the getter functions
JSON is nothing but a key-value representation. It's not hard to get a hang of it. Your code should be something like this,
Update: This will only print URL's which have size = medium
String response = "{\"album\":[{\"name\":\"DD Y Ponle Play\",\"artist\":\"Jumbo\",\"id\":\"2528039\",\"url\":\"http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play\",\"image\":[{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"small\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"medium\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"large\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"extralarge\"}]}]}";
JSONObject myObject = new JSONObject(response);
JSONArray myArray = myObject.getJSONArray( "album" );
for(int i=0; i<myArray.length(); i++)
{
JSONObject myIterator = myArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
if(myInnerIterator.has( "size" ))//check if 'size' key is present
if(myInnerIterator.getString( "size" ).equalsIgnoreCase( "medium" ))
System.out.println( myInnerIterator.getString( "#text" ) );
}
}
As mentioned by Raghunandan, you're extracting a JSONObject, when you need to be extracting a JSONArray, and then from that array, you can extract a JSONObject.
Try using a library such as GSON to make this task easier, or refer to this tiny JSON library I wrote.
It's pretty simple actually to parse a JSON array:
JSONArray jsonarray = new JSONArray("album");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String url = jsonobject.getString("url");
}
Hope it helps!!!
To find the url of the images "medium" I did like this:
ArrayList<String> listUrl = new ArrayList<String>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject myIterator = null;
try {
myIterator = jsonArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
String s = myInnerIterator.getString( "size" )+myInnerIterator.getString("#text");
if (s.contains("medium") && s.contains("https")){
listUrl.add (s.replace("medium",""));
Log.i("RESPONSE",s.replace("medium",""));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I think there must be much better ... but it does the job!
I have a Restaurant List Object and also have a Cuisine List Object in that Restaurant List. How to Loop to show all cuisine data (New American, Japanese, Asia).
public class RestaurantList {
#SerializedName("restaurant_id")
#Expose
private String restaurantId;
#SerializedName("restaurant_name")
#Expose
private String restaurantName;
#SerializedName("cuisine")
#Expose
private List<Cuisine> cuisine = null;
public List<Cuisine> getCuisine() {
return cuisine;
}
public void setCuisine(List<Cuisine> cuisine) {
this.cuisine = cuisine;
}
}
In Restaurant RVAdapter, onBindViewHolder();
List<RestaurantList> mRestaurantList;
List<Cuisine> cuisineList = restaurantList.getCuisine();
String strCuisine = "";
for (int i = 0; i < cuisineList.size(); i++) {
strCuisine.concat(cuisineList.get(i).getCuisineName());
strCuisine.concat(",");
Log.i("Cuisine", cuisineList.get(i).getCuisineName());
holder.tv_restaurant_cuisine.setText(" " + cuisineList.get(i).getCuisineName());
}
Json Array;
[
{...},
{
"restaurant_id": "41",
"restaurant_name": "Shwe Lar Food Restaurant",
"cuisine": [
{
"cuisine_name": "New American"
},
{
"cuisine_name": "Japanese"
},
{
"cuisine_name": "Asia"
}
],
}
]
Use Below Method to parse your data:
I remove last , after array and {...}
private void parseJson(String jsonDataResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonDataResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String restaurant_id = jsonObject1.optString("restaurant_id");
String restaurant_name = jsonObject1.optString("restaurant_name");
JSONArray jsonArray1 =jsonObject1.getJSONArray("cuisine");
System.out.println("restaurant_id="+restaurant_id);
System.out.println("restaurant_name="+restaurant_name);
for(int j=0;j<jsonArray1.length();j++)
{
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
String cuisine_name = jsonObject2.optString("cuisine_name");
System.out.println("cuisine_name="+cuisine_name);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
System.out.println("Sentence is:: " + s);
System.out.println("Id is:: " + id);
System.out.println("text file is:: " + txtFile);
}
} catch (JSONException e) {
e.printStackTrace();
}
currently, the above code is able to print out all the records. However, I would like to change the system.out.println into return variables such as return ID, return txtFile, return sentence. How to do that?
Create an Object. use an arraylist to store your object and use it later.
public class myItem{
String sentence;
int id;
String txtfile;
public myItem(){
}
public String getSentence(){
return sentence;
}
public setSentence(String s){
this.sentence = sentence;
}
}
public void yourFunction(){
try {
ArrayList <myItem> myList = new ArrayList();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
myItem newItem = new myItem();
newItem.setSentence(s);
myList.add(newItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I agree with what Zhi Kai said in the comment.
PS. I can't comment yet so I'm writing this as an answer.
Create a POJO and u se data structure. In your case you are using a for loop so I assume you need to return a list of values from your JSONArray.
Here's what you can do.
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
Updated:
public class YourObject {
private String id;
private String txtFile;
private String sentence;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxtFile() {
return txtFile;
}
public void setTxtFile(String txtFile) {
this.txtFile = txtFile;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
public List<YourObject> returnObject(){
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
}
Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");
I have a JSON data in the following format,
[
{
"name": "France",
"date_time": "2015-05-17 19:59:00",
"dewpoint": "17",
"air_temp": "10.8"
},
{
"name": "England",
"date_time": "2015-05-17 19:58:48",
"dewpoint": "13",
"air_temp": "10.6"
},
{
"name": "Ireland",
"date_time": "2015-05-17 19:58:50",
"dewpoint": "15",
"air_temp": "11.1"
}
]
I have a Google map set up already for the Android app, so i have a pass the name value between two activity(GoogleMaps.java & WeatherInfo.java), now when i click a point in Google Map, it will pass the name to WeatherInfo.java, i want get the weather data for that name.
for example: i click France point in the map, The WeatherInfo.class will get the name is "France" and print out the "date_time, dewpoint, air_temp" for that point.
My question is how can i get the Json data parsed only for the point i clicked in the map? Can anyone look at the for loop in my WeatherInfo.java class?
WeatherInfo.java
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String date_time = c.getString(TAG_DATE);
String temp = c.getString(TAG_TEMP);
String dewpoint = c.getString(TAG_DEWPOINT);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_DATE, date_time);
contact.put(TAG_TEMP, temp);
contact.put(TAG_DEWPOINT, dewpoint);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
String name = jsonObject.getString("name");
String date = jsonObject.getString("date_time");
...
}
Or
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
City city = new City();
city.name = jsonObject.getString("name");
...
}
You could use Jackson json parser as follows:-
you will need a value object for the point data.
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Point {
private final String name;
private final String dateTime;
private final int dewpoint;
private final double airTemp;
#JsonCreator
public Point(#JsonProperty("name") final String name, #JsonProperty("date_time") final String dateTime, #JsonProperty("dewpoint") final int dewpoint, #JsonProperty("air_temp") final double airTemp) {
this.name = name;
this.dateTime = dateTime;
this.dewpoint = dewpoint;
this.airTemp = airTemp;
}
public String getName() {
return name;
}
public String getDateTime() {
return dateTime;
}
public int getDewpoint() {
return dewpoint;
}
public double getAirTemp() {
return airTemp;
}
}
Then this Jackson Object Mapper
// 2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
Point[] points = mapper.readValue(new File("points.json"), Point[].class);
for (Point point : points) {
System.out.println("" + point.getName());
System.out.println("" + point.getDateTime());
System.out.println("" + point.getDewpoint());
System.out.println("" + point.getAirTemp());
}