I have a problem to load this json in a JSONObject, i tried some combinations but it didn't work, for example i was able to load the Openweather JSON format easy but this one i got nothing on my Log as output
this is the format of Json:
{
"marcadores": [
{
"lat": 38.632682,
"id": 1,
"nombre": "Les Urques",
"mar": "appvalenciaplayas/static/images/mar/moderado.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_S2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 29,
"lon": 0.032945
},
{
"lat": 40.078478,
"id": 2,
"nombre": "Cala d'Orpesa la Vella",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.134357
},
{
"lat": 40.008969,
"id": 3,
"nombre": "El Serradal",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.034107
},
Thanks.
please put your response as a string in JSONObject
i am showing to you how to get all fields values like this
please read my code and apply my code as per your need.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}
}catch(Exception e)
{
e.printStackTrace();
}
Parse your JSON as follows
String str = "your_json_here";
try {
JSONObject jsonObject = new JSONObject(str);
JSONArray jsonArray = jsonObject.getJSONArray("marcadores");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject elementJsonObject = jsonArray.getJSONObject(i);
String id = elementJsonObject.getString("id");
// all fields to be accessed as above
}
} catch (JSONException e) {
e.printStackTrace();
}
Firstly, you need to create a POJO with attributes lat,id,nombre...
Read JSON array elements and convert JSON to Class (You can use jackson or Gson)
Use your object whatever you want
In addition this code piece may help you, but auto convertion is more pretty with some libs.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}}catch(Exception e) { e.printStackTrace(); }
Some other helpful links
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/
Happy coding.
you can use Gson framework. You create a model class with the same Json response attributes/structure . This way you do not need to use getString( ) and getObject().
Example: https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Related
During Login time i got this error, please don't downgrade this if you know any solution please guide me. I also checked different stack overflow post but they all are talking about trim the string or other solution with retrofit but i can't solve it. I use volley.
My Json File:-
{
"error": false,
"user": [
{
"user_id": "123",
"customer_name": "Abc",
"email": "abc#example.com",
"salt": "123abc",
"phone": "1234567890",
"address": "Enter Address",
"postal_code": "1234"
}
]
}
This is my Java Class :-
#Override
protected String doInBackground(Boolean... booleen) {
ExampleApi exampleApi = new ExampleApi();
LoginUser result;
try {
result = exampleApi.loginPost(sharedPreferences.getString("abc_id", ""), semail, fcmToken, spassword);
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jObj = new JSONObject(json);
Log.e("result1", String.valueOf(jObj));
if (jObj.getString("error").equalsIgnoreCase("false")) {
JSONArray jsonArray = jObj.getJSONArray("user");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
return "true";
}else {
String errormsg = jObj.getString("error_msg");
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
Log.e("error", e.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
Can you try initializing Gson as below
Gson gson = new GsonBuilder()
.setLenient()
.create();
Possibly there could be an issue in the expected JSON.
Check whether the properties of user object (user_id, customer_name. etc) are in correct format which is equal to the object received as response.
ps: If user_id is an Integer in your user object also it should be an Integer
In my case, this error was generated because of non UTF-8 json file encoding. When I convert it to UTF-8 all started to work.
I have a bug in the code, but I can not find it. I have to read the message and the code from the JSON request below.
try {
Log.d("qwertz", json);
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("win"))
{
showDialog("Du hast etwas gewonnen", message,code);
}
else if (code.equals("false"))
{
showDialog("Du hast leider nichts gewonnen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
That is a JSON example
{
"server_response": {
"code": "win",
"message": "Du hast einen PzKpfw S35 739(f) gewonnen"
}
}
I advice you not to process json directly by yourself, instead you can use many libraries that will do the job for you. To mention you can use jackson or gson.
If you still want to correct your code you can try this:
JSONObject response = jsonObject.getJsonObject("server_response");
String code = response.getString("code");
I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}
I use code above to parse JSON in a try-catch.
JSONArray jsonRootObject = new JSONArray(text);
JSONArray jsonArray = jsonRootObject.optJSONArray(2);
name = jsonArray.toString();
Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
I use 2 as index in code below, because I would get values from candidates. I think, that is strange, because there isn't key-value pairs in array. I would like to get only the first key from this array (In this example subtest1.), its value isn't make sense.
{
"images": [
{
"time": 2.86091,
"transaction":
{
"status": "Complete",
"subject": "test2",
"confidence": 0.77,
"gallery_name": "gallerytest1",
},
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
} ]
}
Try this and see if it solves your problem
JSONArray CandidatesArr = new JSONArray(jsonRootObject.getString("candidates"));
JSONObject CandidatesOBJ = CandidatesArr.getJSONObject(0);
String name=CandidatesOBJ.getString("subtest1");
Edit
To check if your key subset1 exists or not try the following code:
String name=""
if(CandidatesOBJ.has("subtest1")){
name=CandidatesOBJ.getString("subtest1");
}
your parser should be like.FYI JSONArray does not have key-value pairs but JSONObject does.
JSONObject root = new JSONObject(text);
JSONArray jarray = root.optJSONArray("images);
if(jarray != null){
JSONObject jObject = jarray.optJSONObject(0);
if(jObject != null){
JSONArray candidates = jObject.optJSONArray("candidates");
JSONObject jObj = jarray.optJSONObject(0);
if(jObj != null){
String subTest = jObj.optString("subtest1");
}
}
}
How to parse this below json response. I am developing a booking app. The response i got from the server is
{"HotelInformationResponse": {
"#hotelId": "210985",
"customerSessionId": "0ABAA826-9AAF-5791-3692-A03326791310",
"HotelSummary": {
"#order": "0",
"hotelId": 210985,
"name": "Seattle Marriott Waterfront",
"address1": "2100 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"propertyCategory": 1,
"hotelRating": 4,
"tripAdvisorRating": 4,
"locationDescription": "Near Seattle Aquarium",
"highRate": 645,
"lowRate": 279,
"latitude": 47.61016,
"longitude": -122.34651
},
"HotelDetails": {
"numberOfRooms": 358,
"numberOfFloors": 8,
"checkInTime": "4:00 PM",
"checkOutTime": "12:00 PM",
"propertyInformation": "Pets not allowed Check-in time starts at 4 PM Check-out time is Noon ",
}
Any method is appreciated
I hope this code can help u
public static String Profile_response(String response){
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForcitydetail1(jsonobject.getString("HotelInformationResponse"));
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
public static void parseForcitydetail1(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Hotal_ID.add(jsonobject.getString("#hotelId"));
customer_ID.add(jsonobject.getString("customerSessionId"));
}
parseForcitydetail2(jsonobject.getString("HotelSummary"));
}catch (Exception e) {
System.out.println(e.toString());
}
}
public static void parseForcitydetail2(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Order.add(jsonobject.getString("#order"));
hote_ID.add(jsonobject.getString("hotelId"));
Name.add(jsonobject.getString("name")); Address.add(jsonobject.getString("address1"));....
City.add(jsonobject.getString("city"));
StateProvinceCode.add(jsonobject.getString("stateProvinceCode")); PostalCode.add(jsonobject.getString("postalCode"));
CountryCode.add(jsonobject.getString("countryCode"));
PropertyCategory.add(jsonobject.getString("propertyCategory")); HotelRating.add(jsonobject.getString("hotelRating"));....
TripAdvisorRating.add(jsonobject.getString("tripAdvisorRating"));
LocationDescription.add(jsonobject.getString("locationDescription")); Latitude.add(jsonobject.getString("latitude"));
Longitude.add(jsonobject.getString("longitude"));
}
}catch (Exception e) {
System.out.println(e.toString());
}
}
This Same process with "HotelDetails" Parsing
Enjoy !
You may use JSONArray and JSONObject to parse it manually. but its boring and may require extra attention to keys while running in loops. The easiest and highly recommended way is to use Google Gson library to handle this automatically.
Using JSONOBject, JSONArray to contain data like JSONObject, JSONArray
Using methods like: getJSONObject(), getString(), getXXX(). . to get data which you want.
with XXX - data type like int, string
You will understand how to parse JSON in Android easily with the link which describes how to parse JSON clearly (Example):
http://www.technotalkative.com/android-json-parsing/
private JSONObject jObject;
jObject = new JSONObject(your response as string);
//this will give you json object for HotelInformationResponse
JSONObject menuObject = jObject.getJSONObject("HotelInformationResponse");
by this way you can get values
String hotelId = menuObject.getString("#hotelId");
String customerSessionId = menuObject.getString("customerSessionId");
//...rest are same do same thing for HotelDetails
for extra information Check this link