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());
}
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}
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();
}
}
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'm having trouble retrieving the Id from a JSONObject and passing it to a String to record the Id of that players particular puzzle but on the line String idString = obj.getString("Id");
"I get org.json.JSONException: No value for Id"
I'm getting this information by calling to the server in this class which checks the username and password of the player.
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;
public class GetTodaysPuzzle implements OnRetrieveHttpData {
public String GetTodaysPuzzle(String mUserName, String mPassword)
{
RetrieveHTTPData GetTodayspuzzle = new RetrieveHTTPData(this);
return GetTodayspuzzle.GetResponseData("urlString" + mUserName + "&password=" + mPassword);
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Server Response", httpData);
}
class GetTodaysPuzzleTask extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
// Get response from server
String json = GetTodaysPuzzle(params[0], params[1]);
// Check if a puzzle was returned
if (json.contains("The request is invalid"))
{
return false;
}
try
{
// Calculate today's date in order to set wordsearch date
Time today = new Time();
today.setToNow();
String formattedDate = Dates.ConvertUStoUK(today.year + "-"
+ (today.month + 1) + "-" + today.monthDay);
// Create wordsearch
WordSearch wordSearch = WordSearch.CreateWordSearch(json,
formattedDate);
if (wordSearch == null)
{
return false;
}
// Save wordsearch to collection
WordSearchDatabase.Add(wordSearch);
// WordSearchDatabase.Save();
return true;
}
catch (Exception e)
{
Log.e("GetTodaysPuzzleTask", e.getMessage());
return false;
}
}
}
}
And then stores all the information into JSONArrays in the Wordsearch class.
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class WordSearch {
public String Id;
public String Date;
public List<Word> Words;
public Letter[] Letters;
public final int NUM_OF_ROWS;
public final int NUM_OF_COLS;
public int Score = -1;
private boolean containsSolution = false;
public boolean canBeSubmitted = true;
private boolean complete = false;
private boolean submitted = false;
public static WordSearch CreateWordSearch(String json, String date)
{
List<Word> listOfWords = new ArrayList<Word>();
List<String> listOfRows = new ArrayList<String>();
try
{
// Create a JSON Object from JSON string
JSONObject obj = new JSONObject(json);
// Get Id
String idString = obj.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = obj.getJSONArray("Words");
JSONArray puzzleArray = obj.getJSONArray("Grid");
// Parse Words array
for (int i = 0; i < wordsArray.length(); i++)
{
String name = wordsArray.getString(i);
Word word = new Word(name);
listOfWords.add(word);
}
// Parse Puzzle
for (int k = 0; k < puzzleArray.length(); k++)
{
String puzzle = puzzleArray.getString(k);
listOfRows.add(puzzle);
}
// Create WordSearch
return new WordSearch(idString, date, listOfWords, listOfRows,
false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
This is the first time I have used API servers and JSONObject's in Android so any help would be much appreciated. Thank you.
You are getting this error because your response JSON doesn't have "Id" as a key, It only has "Puzzle" as you can see:
{
"Puzzle": {
"Id": "8fb25209-863a-410b-a440-b5b57a903ee1",
"Words": ["CHATEAUX", ...],
"Grid": ["TLIOFSHTRC", ...]
}
}
You need to first get the "Puzzle" object first and then you can get the "Id" from that object.
JSONObject obj = new JSONObject(json);
JSONObject puzzle = obj.getJSONObject("Puzzle");
String idString = puzzle.getString("Id");
....
Id is in the puzzle element so it should be
JSONObject obj = new JSONObject(json);
//get puzzle object
JSONObject puzzle = obj.getJSONObject("Puzzle");
// Get Id
String idString = puzzle.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = puzzle.getJSONArray("Words");
JSONArray puzzleArray = puzzle.getJSONArray("Grid");