I am working with volley for network calling in android. my webservice is send me response object like that
{
"Code": 200,
"Message": "Record Found",
"Result": {
"deviceid": 10,
"udid": "359447060356151",
"businessid": 1,
"usertype": "Merchant"
}
}
now i want to read the code and message from this object. but failed to do so. I am using this code for getting this data.
JSONObject jsonObj = new JSONObject(response);
JSONObject userDetails = jsonObj.getJSONObject("Result");
LoginResponse entryObj = new LoginResponse();
entryObj.businessid = userDetails.getInt("businessid");
lr.businessid = entryObj.businessid;
Utilities.businessId = lr.businessid;
help me to read the code from this object. i am not getting the exact solution.
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");
This is how you read code and message.
Hey you can get code string from json using parsing,
JsonObject jsonObj=new jsonObject(response);
String code=jsonObj.optString("Code");
Do like this:
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");
Related
I am working on Retrofit Post but i am getting slashes () when sending data to post method. Here i need to send the complete json object data to post method, so i converted the json object to String . But when sending slashes are appending to request. I also replaced the slashes to empty string but it is not working. Any one please help me.
code:
private void favouriteadding(String restaurant_id, String restaurant_name, JsonArray Restaurant_info) {
String replac = Restaurant_info.toString(); // jsonarray
replac = replac.replace("[", "")
.replace("]", "")
.trim();
Log.v("Tag_replacestring",""+replac);
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject userfav = new JsonObject();
userfav.addProperty("user_id", m_sharedPreference.getString("userid", ""));
userfav.addProperty("restaurant_id", restaurant_id);
userfav.addProperty("restaurant_name", restaurant_name);
userfav.addProperty("restaurant_info",replac.replace('\\','"') );
Log.v("Tag_postdata",""+userfav);
serviceClient.list_fav(userfav, listfavcallback);
}
Log:
Tag_replacestring: {"status":"enabled","features":"No Alcohol Available","cuisines":"Hyderabadi","Mughlai","Biryani","Chinese","cost":850.0,"createdAt":"2018-03-08 09:26:13","branch_id":"5aa146ce1d41c86e73e11d79","stats":{},"dishes":"Hyderabadi Dum Biryani","Mutton Biryani}
but getting like this with slashes:
Tag_postdata:
{"user_id":"","restaurant_id":"5aa148051d41c86e73e11d7a","restaurant_name":"Hotel Shadab","restaurant_info":"{\"status\":\"enabled\",\"features\":\"No Alcohol Available\",\"cuisines\":\"Hyderabadi\",\"Mughlai\",\"Biryani\",\"Chinese\",\"cost\":850.0,\"createdAt\":\"2018-03-08 09:26:13\",\"branch_id\":\"5aa146ce1d41c86e73e11d79\"
I am getting Json Response from the server, And mapping JSON data with Java class.
Here is code.
Gson gsonObj = new Gson();
AppointmentData appointmentData = gsonObj.fromJson(response, AppointmentData.class);
its working fine until response changes sometimes.
Here is response screenshot.
Now look at the response final_slots in response is sometimes as JSON Object and sometimes JSONArray. if final_slots is JSONArray then my Mapping code works, but if its is JSON Object then I have to change the logic. here is my code what I m doing in both cases
JSONObject JsonObjResponse = new JSONObject(response);
JSONObject jsonDataObj = JsonObjResponse.getJSONObject("data");
Object json = new JSONTokener( jsonDataObj.get("final_slots").toString()).nextValue();
/*******************************If response (final_slots) is JsonObject******************************/
if (json instanceof JSONObject) {
JSONObject jsonObj = jsonDataObj.getJSONObject("final_slots");
appointmentData=new AppointmentData();
AppointmentSettingData appointmentSettingData=new AppointmentSettingData();
JsonObjResponse.getString("data");
User userObj=new User();
JSONObject userJsonData= JsonObjResponse.getJSONObject("data").getJSONObject("user");
userObj.pk=userJsonData.getInt("pk");
userObj.unique_id=userJsonData.getString("unique_id");
userObj.fk_role=userJsonData.getInt("fk_role");
userObj.fk_status=userJsonData.getInt("fk_status");
userObj.fk_hospital=userJsonData.getInt("fk_hospital");
userObj.fk_department=userJsonData.getInt("fk_department");
userObj.fk_sub_department=userJsonData.getInt("fk_sub_department");
userObj.user_slug=userJsonData.getString("user_slug");
userObj.first_name=userJsonData.getString("first_name");
userObj.last_name=userJsonData.getString("last_name");
userObj.user_name_en=userJsonData.getString("user_name_en");
userObj.user_name_ar=userJsonData.getString("user_name_ar");
userObj.username=userJsonData.getString("username");
userObj.password=userJsonData.getString("password");
userObj.email=userJsonData.getString("email");
userObj.contact=userJsonData.getString("contact");
// userObj.qualification=userJsonData.getString("qualification");
userObj.mobile=userJsonData.getString("mobile");
userObj.appointment_duration=userJsonData.getInt("appointment_duration");
userObj.registration_date=userJsonData.getString("registration_date");
userObj.activation_code=userJsonData.getString("activation_code");
userObj.email_verified=userJsonData.getInt("email_verified");
userObj.device_token=userJsonData.getString("device_token");
userObj.device_type=userJsonData.getString("device_type");
userObj.device_id=userJsonData.getString("device_id");
userObj.created_at=userJsonData.getString("created_at");
userObj.updated_at=userJsonData.getString("updated_at");
// userObj.created_at=userJsonData.getString("created_by");
userObj.updated_by=userJsonData.getInt("updated_by");
appointmentSettingData.setUser(userObj);
appointmentData.setData(appointmentSettingData);
int i=0;
List<Slots> final_slots=new ArrayList<Slots>();
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
totalslots = final_slots.size();
totalslotLines = totalslots / 5;
} else if (json instanceof JSONArray) {
/*******************************If response (final_slots) is JsonArray******************************/
appointmentData = gsonObj.fromJson(response, AppointmentData.class);
totalslots = appointmentData.data.final_slots.size();
totalslotLines = totalslots / 5;
}
Issue:
when in response final_slots comes as json Object. As you can that when it final_slots is as jsonObject then I am getting inside JSON Object by the index as the name of JSON Object(i.e jsonObj.getJSONObject(""+i).get("start")). I am having issue when index is missing (you can see response upload image), because i am getting by the index, assuming that index will not miss in response. but I m fail here.
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
what I need:
I want to appointmentData object a compelete object which provide me all response either jsonArray in response or JSonobject in response.
I will be thankful to you for my assistance.
I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?
Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");
Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");
You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}
I am using Retrofit which uses GSON for parsing.The server will check the parameter i am sending and returns two responses Accordingly.
If the parameter is valid i am getting the following response
[
true
]
If it is not valid then i get response as,
[
"Sorry, <em class=\"placeholder\">names#gmail.inp</em> is not recognized as a user name or an e-mail address."
]
This is the call method i am using.
#Override
public void onResponse(Call<String> call, Response<String> response) {
mProgressBar.setVisibility(View.GONE);
Log.d("Response ", ""+response);
}
here response.body giving me as null. But there is a response.which is viewable in OKHttp Log.
you can try this
JSONArray jArray=new JSONArray(yourString);
String str=jArray.getString(0);;
if(str.equalsIgnoreCase("true")
{
//your code
}else
{
}
JSONArray jarray = new JSONObject(jsonString);
for (int i = 0; i < jarray.length(); i++) {
String string = jarray.getString(i);
log.e("String",string);
}
that's working great. Please try this.
You can use JsonParser provided by Gson. It will parse the json input to dynamic JsonElement.
Look at MByD example:
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
since the server return diffrent codes
can you try
Call<Void>
and check the response code
this might work for now until you know what is wrong void will not parse any thing so it shouldn't cause a crash
///////
did you try
Call<ArrayList<String>>
also are you sure the server returns 200 in both cases ?
I'm trying to get a particular value from a field within a JSON file. This is my first time working with a JSON file so I'm not sure if I'm doing it correctly.
try {
URL url = new URL(API_URL + city +".json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
This block would get the JSON from a weather website and then return the JSON as a string. This string would then be used below. Unfortunately whenever I run this app in Android Studio and go through the logs the logs constantly say that there was no value in weather.
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String weather = object.getString("weather");
Toast.makeText(MyActivity.this, "There is rain", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
What I'm trying to do is grab information from the weather section
Here is the JSON link I'm trying to parse from. This text box thought there were too many links in the JSON response for me to post it here. I'm trying to figure out what is going on and any help would be greatly appreciated.
You can print out response to see if it is exactly your JSON or not.
Assume you get the JSON String correctly.
JSONObject object = new JSONObject(response);
String weather = object.getString("weather");
However, if the JSON your obtained is exactly your response, the above code do not work because there is not weather String. The root only contain response and current_observation.
If what you what to get is weather under current_observation, you should use the code below.
JSONObject object = new JSONObject(response);
JSONObject current_obs = object.getJSONObject("current_observation");
String weather = current_obs.getString("weather"); // Clear
JSONObject object = (JSONObject) new JsonObject(responseString);
String weather = object.getString("weather");
First you need to get your response in string.
Now,start json parsing as per response.
OR
You can use Gson class as well for json parsing.
Get json value from JSONObject:
{"weather":"sunny"}
code snippet to parse the JSONObject.
JSONObject object = new JsonObject(response);
String weather= object.getString("weather");
Get json value from JSONArray:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
code snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
Hope it'll help you.
I have a sample Weather app done using open weather map api. It has all you asked for.
Code here:
http://opensourceandroid.in/weather_forecast.html