How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.
Related
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.
Here's the code
Utils class
public class WeatherUtils {
public WeatherUtils(){}
public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){
ArrayList<Weather> weatherList = new ArrayList<>();
try {
JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
JSONArray array = reader.getJSONArray("list");
for (int i = 0; i<array.length(); i++){
JSONObject secondReader = array.getJSONObject(i);
JSONObject dataObject = secondReader.getJSONObject("main");
for (int j = 0; j<dataObject.length(); j++){
currentTemp = dataObject.getDouble("temp");
minTemp = dataObject.getDouble("temp_min");
maxTemp = dataObject.getDouble("temp_max");
airPressure = dataObject.getDouble("pressure");
}
weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
}
} catch (JSONException e) {
e.printStackTrace();
}
return weatherList;
}
}
MainActivity
Double a,b,c,d;
a = 0.0;
b = 0.0;
c = 0.0;
d = 0.0;
ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
System.out.println(weathers);
JSON structure
{
"cod": "200",
"message": 0.0074,
"cnt": 40,
"list": [
{
"dt": 1559131200,
"main": {
"temp": 22.1,
"temp_min": 21.32,
"temp_max": 22.1,
"pressure": 1012.31,
"sea_level": 1012.31,
"grnd_level": 976.84,
"humidity": 92,
"temp_kf": 0.78
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": {
"all": 89
},
"wind": {
"speed": 3.08,
"deg": 213.025
},
"rain": {
"3h": 0.875
},
"sys": {
"pod": "d"
},
"dt_txt": "2019-05-29 12:00:00"
},
{
Of course, there are more data. I've posted one "block"
How I may fix that?
Well, given that you just want to "test" the json parsing, you have few options but let's go with a simple one. But first, I would say to extract the parser and put it in its own class/method so it becomes easier to test, something like this:
public class WeatherUtils {
public WeatherUtils(){}
public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){
final ArrayList<Weather> weatherList = new ArrayList<>();
try {
final JSONObject response = httpCall();
weatherList = mapWeatherResponse(response);
} catch (JSONException e) {
e.printStackTrace();
}
return weatherList;
}
public static List<Weather> mapWeatherResponse(JSONObject reader){
final ArrayList<Weather> weatherList = new ArrayList<>();
JSONArray array = reader.getJSONArray("list");
for (int i = 0; i<array.length(); i++){
JSONObject secondReader = array.getJSONObject(i);
JSONObject dataObject = secondReader.getJSONObject("main");
for (int j = 0; j<dataObject.length(); j++){
currentTemp = dataObject.getDouble("temp");
minTemp = dataObject.getDouble("temp_min");
maxTemp = dataObject.getDouble("temp_max");
airPressure = dataObject.getDouble("pressure");
}
weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
}
}
}
Test the response parser with a junit test:
You can create a junit test like this:
public class WeatherUtilsTest {
#Test
public void parserResponseTEst() {
final List<String> expectedResponse = new ArrayList<>();
//fill the expectedResponse with the correspondent values
final String json = "{\n" +
" \"cod\": \"200\",\n" +
" \"message\": 0.0074,\n" +
" \"cnt\": 40,\n" +
" \"list\": [\n" +
" {\n" +
" \"dt\": 1559131200,\n" +
" \"main\": {\n" +
" \"temp\": 22.1,\n" +
" \"temp_min\": 21.32,\n" +
" \"temp_max\": 22.1,\n" +
" \"pressure\": 1012.31,\n" +
" \"sea_level\": 1012.31,\n" +
" \"grnd_level\": 976.84,\n" +
" \"humidity\": 92,\n" +
" \"temp_kf\": 0.78\n" +
" },\n" +
" \"weather\": [\n" +
" {\n" +
" \"id\": 500,\n" +
" \"main\": \"Rain\",\n" +
" \"description\": \"light rain\",\n" +
" \"icon\": \"10d\"\n" +
" }\n" +
" ],\n" +
" \"clouds\": {\n" +
" \"all\": 89\n" +
" },\n" +
" \"wind\": {\n" +
" \"speed\": 3.08,\n" +
" \"deg\": 213.025\n" +
" },\n" +
" \"rain\": {\n" +
" \"3h\": 0.875\n" +
" }\n" +
" }]\n" +
" }";
final List<String> response = WeatherUtils.mapWeatherResponse(new JSONObject(json));
assertEquals(expectedResponse, response);
}
}
There is nothing wrong with the JSONObject parser you are doing. You mentioned the link you are using in Utils is correct, do you get a proper response when you test it in your browser, postman, insomnia?
OBS JSONObject reader = new JSONObject("https://api..."); does not fetch anything, what you are doing there is creating a JSONObject from the given String, i.e. "https://....". To fetch the data you need to implement some http client. Here is an example https://stackoverflow.com/a/4457526/761668
You're not getting the response from the server, you're trying to initialize a JSONObject with the URL.
To retrieve it you should replace this line:
JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
with this code:
HttpURLConnection conn = null;
String data = null;
try {
conn = (HttpURLConnection) new URL("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...").openConnection();
conn.setRequestMethod("GET");
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
data = sb.toString();
} catch (Exception e) {
// do something
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
// do something
}
}
}
JSONObject reader = new JSONObject(data);
This code will retrieve the JSON object from the endpoint and convert it to a String object. Then you can create a JSONObject with it.
This is the function that's giving me the problem:
public String URLToJson() {
String result = "";
String jsonString = ReadingURL(" here goes my URL that reads a JSON ");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
JSONArray data = jsonResult.getJSONArray("Configuracion");
if (data != null) {
for (int i = 0; i <= data.length(); i++) {
result = result + "Dirección: " + data.getJSONObject(i).getString("Direccion") + "\n";
result = result + "Cédula: " + data.getJSONObject(i).getString("Cedula") + "\n";
result = result + "Nombre: : " + data.getJSONObject(i).getString("Nombre") + "\n";
result = result + "Teléfono : " + data.getJSONObject(i).getString("Telefono") + "\n";
result = result + "Hacienda: " + data.getJSONObject(i).getString("Hacienda") + "\n";
}
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And then this comes up:
`W/System.err: org.json.JSONException: Value {"Direccion":"Somewhere","Cedula":"111111","Nombre":"Something","Telefono":"2222-2440","Hacienda":"Something"} at Configuracion of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:588)
at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:977)
W/System.err: at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)W/System.err: org.json.JSONException: Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray`
ReadingURL basically reads the content of an URL, that has the JSON in String.
From the exception it's clear that the JSON string returned by the URL is of type JSONObject not of JSONArray .
Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray
JSON object will starts with { & ends with }
{
"KEY1":"VALUE1",
"KEY2":"VALUE2"
}
and JSON array will starts with [ and ends with ] .
[
{"KEY1":"VALUE1","KEY2":"VALUE2"},{"KEY1":"VALUE1","KEY2":"VALUE2"}
]
So you are getting this exception because you are trying to convert JSON object to JSON array.
to Deepak Gunasekaran
public String URLToJson() {
String result = "";
String jsonString = ReadingURL("http://deliciasmarinas.avancari.co.cr/app/tiquete.php?factura=414696772");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
for (int i = 0; i <= jsonResult.length(); i++) {
result = result + "Dirección: " + jsonResult.get("Direccion") + "\n";
result = result + "Cédula: " + jsonResult.get("Cedula") + "\n";
result = result + "Nombre: : " + jsonResult.get("Nombre") + "\n";
result = result + "Teléfono : " + jsonResult.get("Telefono") + "\n";
result = result + "Hacienda: " + jsonResult.get("Hacienda") + "\n";
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And now it just shows
W/System.err: org.json.JSONException: No value for Direccion
at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:978)
at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)
[
{
"orderDetails": [
{
"account_name": "akhil_kotak",
}
]
}
]
How to get the account name from this json, i tried doing this
String response = new String(responseBody);
//ON SUCCESS GETS JSON Object
JSONArray array = new JSONArray(response);
JSONObject obj =
array.getJSONObject(0).getJSONArray("orderDetails").getJSONObject(0);
txt_accountName.setText(obj.getString("account_name"));
If anyone can help, that would be awesome.
Thanks
Your JSON is invalid.
You can change to this.
[
{
"orderDetails": [
{
"account_name": "akhil_kotak"
}
]
}
]
Just change "account_name": "akhil_kotak" , to "account_name": "akhil_kotak" .
Just remove the comma in your JSON .
Try this .
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray orderDetails = jsonObject.getJSONArray("orderDetails");
for (int j = 0; j < orderDetails.length(); j++) {
JSONObject jsonObject2 = orderDetails.getJSONObject(j);
String account_name = jsonObject2.getString("account_name");
txt_accountName.setText(account_name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if you are using Jackson 2 .. below works
String jsonString = "[{\"orderDetails\": [{\"account_name\": \"akhil_kotak\",}]}]";
ObjectMapper mapper = new ObjectMapper();
JsonNode jnNode= mapper.readTree(jsonString);
Sting accName=jnNode.get("orderDetails").get("account_name").asText();
}
Your JSON is invalid. Remove comma! then:
Create a set of calsses and use Gson!
Add this line to dependencies in your build.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.8.2' //add this line
}
Crate a set of classes:
class SomeListItem {
#SerializedName("orderDetails")
public List<InnerListItem> mOrderDetails;
}
class InnerListItem {
#SerializedName("account_name")
public String mAccountName;
}
And use them like this:
String jsonOutput = "[\n" +
" {\n" +
" \"orderDetails\": [\n" +
" {\n" +
" \"account_name\": \"akhil_kotak\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"]";
Gson gson = new Gson();
Type listType = new TypeToken<List<SomeListItem>>(){}.getType();
List<SomeListItem> parsedJson = gson.fromJson(jsonOutput, listType);
String accountName = parsedJson.get(0).mOrderDetails.get(0).mAccountName;
try this. i am using org.json.simple library.
String str="[{\"orderDetails\": [{\"account_name\": \"akhil_kotak\",}]}]";
JSONParser parser=new JSONParser();
JSONArray array=(JSONArray) parser.parse(str);
JSONObject obj=(JSONObject) array.get(0);
JSONArray nestedArray=(JSONArray) obj.get("orderDetails");
System.out.println("output: "+nestedArray.get(0).get("account_name"));
it's working fine.
I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
i am tring to convert json data from string variable like this example :
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONArray Array = new JSONArray(in);
for (int i = 0; i < Array.length(); i++) {
JSONObject sys = Array.getJSONObject(i);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
};
when i try this code i get this error :
Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONObject
Actually your JSON is wrong formated.
Use string as below
String in = "{\"employees\": [{\"firstName\": \"John\",\"lastName\": \"Doe\"},{\"firstName\": \"Anna\",\"lastName\": \"Smith\"},{\"firstName\": \"Peter\",\"lastName\": \"Jones\"}]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
Your String in is an object with key employees and value JSONArray.
So you need to parse in as a JSONObject and get the JSONArray employees from that object.
Try this
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
try below code:-
JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");
note:-
{} denote JSONObject. ({employe})
[] denote JSONArray. (employee[])
Try to replace this line :
JSONArray Array = new JSONArray(in);
With this :
JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));