{Response: responseCode: 200, graphObject: {"id":"98374978103","birthday":"04\/19\/1991","gender":"male","email":"email#gmail.com","name":"Wasfasf"}, error: null}
I am getting facebook response as above string
How to parse this string.
I am doing it this way
try {
String res = response.toString();
JSONObject obj = new JSONObject(res);
JSONArray arr = obj.optJSONArray("graphObject");
for(int i=0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
String id = jsonObject.optString("id").toString();
String bday = jsonObject.optString("birthday").toString();
String gender = jsonObject.optString("gender").toString();
String email = jsonObject.optString("email").toString();
String name = jsonObject.optString("name").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
It throws the exception :
Unterminated object at character 25 of {Response: responseCode: 200, graphObject: {"id":"983797084978103","birthday":"04\/19\/1991","gender":"male","email":"waleedbinilyas#gmail.com","name":"Waleed Bin Ilyas"}, error: null}
I have done in this way and works fine perfectly
public class SignIn extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//before set conteview
FacebookSdk.sdkInitialize(getApplicationContext());
// AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_signin);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest graphRequest=GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
Log.d("Graph Response",graphResponse.toString());
String myCustomizedResponse = graphResponse.getJSONObject().toString();
Log.d("Ketan_Ramani",graphResponse.getJSONObject().toString());
try {
JSONObject obj = new JSONObject(myCustomizedResponse);
String id = obj.getString("id");
String first_name = obj.getString("first_name");
String last_name = obj.getString("last_name");
String email = obj.getString("email");
Log.d("Id",id);
Log.d("FirstName",first_name);
Log.d("LastName",last_name);
Log.d("Email",email);
} catch (JSONException e) {
Utils.hide_dialog();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I think this would work for you.
try {
String res = response.toString();
JSONObject obj = new JSONObject(res);
JSONArray arr = obj.getJSONArray("graphObject");
for(int i=0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
String id = jsonObject.getString("id").toString();
String bday = jsonObject.getString("birthday").toString();
String gender = jsonObject.getString("gender").toString();
String email = jsonObject.getString("email").toString();
String name = jsonObject.getString("name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Note : I have not tested this code.
The given json is invalid,you can use jsonLint to validte your json Feed
assuming feed below the correct feed
{
"Response": {
"responseCode": 200,
"graphObject": {
"id": "983797088103",
"birthday": "04/19/1991",
"gender": "male",
"email": "email#wamil",
"name": "name"
},
" error": null
}
}
If you are using an IDE like intellij/Android studio use the plugin like Dtonator to generate the Gson DTO's,which will look like this
public class FaceBookResponse {
#SerializedName("Response")
public Response Response;
public static class GraphObject {
#SerializedName("birthday")
public String birthday;
#SerializedName("gender")
public String gender;
#SerializedName("name")
public String name;
#SerializedName("id")
public String id;
#SerializedName("email")
public String email;
}
public static class Response {
#SerializedName("error")
public String error;
#SerializedName("graphObject")
public GraphObject graphObject;
#SerializedName("responseCode")
public int responseCode;
}
}
Now you can simply parse your feed using the below two lines.
private final Gson gson = new Gson();
FaceBookResponse response=mGson.fromJson(json, mClazz);
If you want get a object like graphObject do this:
JSONObject jObj = new JSONObject([jsonString]);
ArrayList<SomeClass> listObj = jObj.getJSONArray("graphObject");
if (listObj.length() != 0){
for (int i = 0; i < listObj.length(); i++) {
JSONObject c = listObj.getJSONObject(i);
c.getString("name");
c.getString("gender");
.
.
.
}
}
Edit: SomeClass = Same Fields that you have in your jsonĀ“s fields, in this case: id,birthday,gender,email,name.
I did it in this way
try {
String id = object.getString("id");
String uname = object.getString("name");
String emailid = object.getString("email");
String gender = object.getString("gender");
String bday = object.getString("birthday");
} catch (Exception e) {
e.printStackTrace();
}
Graph object is an object not array.
public void onCompleted(JSONObject facebookResponseObject, GraphResponse response) {
// Application code
// Log.v("LoginActivity", response.toString());
Log.v("facebook_response", facebookResponseObject.toString());
}}
You are converting response object of type GraphResponse and then doing operations on it.
Instead do this:facebookResponseObject.toString() and then you can easily do this --> Log.e("facebook_response_id",id);
Related
I have fetched JSON data from url using ION library, but I am facing problem in displaying it in a listView in android studio.
I debug it in this way:
JSONObject jsonObject = new JSONObject(String.valueOf(result));
JSONArray jsonArray = jsonObject.getJSONArray("contacts");
and here is the output for debug:
result = {JsonObject#5328} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
result = {JsonObject#5328} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
jsonObject = {JSONObject#5341} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
id is an integer sent form first activity.The code for my activity is given below:
public class ContactsActivity extends AppCompatActivity {
ListView contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Intent intent = getIntent();
contactList = findViewById(R.id.contactList);
int dId = intent.getExtras().getInt("id");
String Sid = new String(String.valueOf(dId));
Context context = getApplicationContext();
Toast.makeText(context, "" + dId, Toast.LENGTH_SHORT).show();
try {
getContacts(Sid);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getContacts(final String Sid) throws Exception {
class Contacts{
String empName;
String designation;
String mobile;
String landlineOffice;
String landlineRes;
String fax;
String email;
public Contacts(String designation, String mobile, String landlineOffice, String landlineRes, String fax, String email) {
this.designation = designation;
this.mobile = mobile;
this.landlineOffice = landlineOffice;
this.landlineRes = landlineRes;
this.fax = fax;
this.email = email;
}
}
Ion.with(this)
.load("http://10.180.243.19:8080/api/departments/" + Sid)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
int id = Integer.parseInt(Sid);
try {
JSONObject jsonObject = new JSONObject(String.valueOf(result));
JSONArray jsonArray = jsonObject.getJSONArray("contacts");
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
}
I expect to display list of contact details of multiple employees in a listview.
I am trying to fetch data from the server and then display it into the app.
I have JSON data as,
{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}
I have my JAVA class as,
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
private void getData() {
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
JSONObject companyData = result.getJSONObject(0);
name = companyData.getString(MON_O);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(name);
}
When I am triying to log the response from the server, I could see that only the COLUMNS value is there where as the DATA is null.
Also, I am getting an error as below,
System.err: org.json.JSONException: Value TIMEID at 0 of type java.lang.String cannot be converted to JSONObject
Why would I get the DATA values from the server as null and how am I suppose to fix the error?
I have referred the links: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
However, these do not seem to help in my case. Please can anyone help?
Try this.....
JSONParser jsonParser = new JSONParser();
jsonObject = jsonParser.getJSONFromUrl(url);
try {
user1 = jsonObject.getJSONArray("COLUMNS");
for (int i = 0; i < user1.length(); i++) {
String value = (String) user1.get(i);
getList.add(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
I observe your json response, i think whatever you are having in column json array there are nothing having string which you are getting thats why you are getting error,
In your response nothing having key value pair so its easy to get String.
so you should getString() instead of getJsonObject()
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
name = result.getString(index);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
index is basically json array index you can put it 0 or something and go for loop if you want.
how to retrieve below json data from server in android? can you please guide me with an example? how to get UserRole from the below url?
http://beta.json-generator.com/api/json/get/4y2NmxAYf
Here's an example to retrieve json data from server
Add this dependency of the Gson library to the App's gradle:
compile 'com.google.code.gson:gson:2.4'
Create a model class
public class UserModel{
public String UserRole;
public String UserName;
public int Id;
public String Email;
public String getUserRole(){
return UserRole;
}
public void setUserRole(String _userRole){
UserRole = _userRole;
}
public String getUserName(){
return UserName;
}
public void setUserName(String _userName){
UserName = _userName;
}
public int getId(){
return Id;
}
public void setId(int _id){
Id = _id;
}
public String getEmail(){
return Email;
}
public void setEmail(String _email){
Email = _email;
}
}
Now use Gson library to convert data from server's response to the above model.(Note: Write these lines in the onPostExecute() of the AsyncTask Class)
#Override
protected void onPostExecute(final Boolean success) {
try {
if (success) {
if (responsecode == 200) {
//GSON responsedata
if(responsedata!=null) {
if (responsedata != "") {
List<UserModel> userlist = new ArrayList<UserModel>();
JSONArray jsonArray = new JSONArray(responsedata);
for (int i = 0; i < jsonArray.length(); i++) {
UserModel item = new UserModel();
item = new Gson().fromJson(jsonArray.getJSONObject(i).toString(), UserModel.class);
userlist.add(item);
}
}
}
} else if(responsecode==401){
// use toast display the specific error
}
}
else {
Toast.makeText(context, responsedata, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Access denied!", Toast.LENGTH_LONG).show();
}
}
catch (Exception e){
if(e!=null){
}
}
}
You are getting json array in response. You can get details from array like:
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String userRole = jsonObject.getString("UserRole");
//Rest of the code....
}
} catch (Exception e) {
e.printStackTrace();
}
Use Below Code to get JsonRespone :
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String API_URL = "http://beta.json-generator.com/api/json/get/4y2NmxAYf";
// Do some validation here
try {
URL url = new URL(API_URL);
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();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
// progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
parseJsonData(response);
}
}
And Parse your data using below method:
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String UserRole = jsonObject1.optString("UserRole");
String UserName = jsonObject1.optString("UserName");
String Id = jsonObject1.optString("Id");
String Email = jsonObject1.optString("Email");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
find API calling code from below Link :
How to use a web API from your Android app
You can use OkHttp to fetch json data from server and use fastjson to parse data.
Add these dependencies to the App's build.gradle:
compile 'com.alibaba:fastjson:1.2.24'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
Then 1.Create a model class:
public class JsonModel {
private String UserRole;
private String UserName;
private int Id;
private String Email;
public String getUserRole() {
return UserRole;
}
public void setUserRole(String UserRole) {
this.UserRole = UserRole;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
#Override
public String toString() {
return "JsonModel{" +
"Email='" + Email + '\'' +
", UserRole='" + UserRole + '\'' +
", UserName='" + UserName + '\'' +
", Id=" + Id +
'}';
}
2.Use OkHttp to fetch json data and use fastjson to parse the data.
class GetJson extends Thread {
private String url;
public GetJson(String url) {
this.url = url;
}
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
final String text = response.body().string();
List<JsonModel> models = JSON.parseArray(text, JsonModel.class);
//Do other things based on models
}
} catch (IOException e) {
e.printStackTrace();
}
}
you can take a look at http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ and try to search more before you start a new topic next time !
Try this,
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://beta.json-generator.com/api/json/get/4y2NmxAYf",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray result = new JSONArray(response);
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String UserRole = c.getString("UserRole");
String UserName = c.getString("UserName");
int Id = c.getInt("Id");
String Email = c.getString("Email");
}
} catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
gradle dependencies for your Android project's app module:
compile 'com.android.volley:volley:1.0.0'
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
{
"status": 200,
"message": "API executed successfully.",
"data": [{
"data": [{
"shopToken": "NQ2",
"Id": 5,
"UserId": 5,
"ShopName": "test",
"ContactName": "test",
"ContactNumber": "test",
"Address": null,
"IsActive": true,
"OwnerName": "Test"
}],
"recordsFiltered": 1,
"recordsTotal": 1,
"draw": 0,
"pageIndex": 0,
"pageSize": 1
}]
}
How can I parse this JSON in Android?
#Override
protected String doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
Request request = new Request.Builder()
.url(Config.GLOPOSNET_URL+"getShops?userToken=NQ2")
.build();
try {
Response response = client.newCall(request).execute();
String res = response.body().string();
try {
JSONObject joa = new JSONObject(res);
int status = joa.getInt("status");
msg = joa.getString("message");
System.out.println("status : "+status);
if (status == 200){
JSONArray infoa = joa.getJSONArray("data");
for (int i=0; i<=infoa.length(); i++){
JSONObject johaa = infoa.getJSONObject(i);
System.out.println("object=== "+johaa.toString());
ModelClassShopList pstShopList = new ModelClassShopList();
pstShopList.getShopToken();
pstShopList.getId(johaa.getInt("Id"));
pstShopList.getUserId(johaa.getString("UserId"));
pstShopList.getShopName(johaa.getString("ShopName"));
pstShopList.getContactName(johaa.getString("ContactName"));
pstShopList.getContactNumber(johaa.getString("ContactNumber"));
pstShopList.getAddress(johaa.getString("Address"));
pstShopList.getOwnerName(johaa.getString("OwnerName"));
String shop_token = pstShopList.getShopToken();
String user_name = pstShopList.getShopName(johaa.getString("UserId"));
String user_type = pstShopList.getContactName(johaa.getString("UserId"));
String user_addres = pstShopList.getContactNumber(johaa.getString("UserId"));
System.out.println("shop token=== "+shop_token);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Config.SHOP_TOKEN, shop_token);
editor.commit();
}
}else {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Light_Dialog_Alert);
builder.setMessage(""+msg);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
To get data array from your JSON String
JSONObject jObject = new JSONObject(youStringData);
JSONArray jArray = jObject.getJSONArray("data");
to get the data inside first one data
for(int i = 0; i < jArray.length(); i++){
JSONArray dataTwo = jArray.getJSONObject(i).getJSONArray("data");;
}
if you want to get other value in the main object you can use
jObject.getInt("status")
Try this,
// Create JSON object
JSONObject jObject = new JSONObject(res);
// Get the outer "data" array
JSONArray dataOuter = jObject.getJSONArray("data");
// Iterate the outer "data" array
for (int i = 0; i < dataOuter.length() ; i++ ) {
JSONObject jObject1 = dataOuter.getJSONObject(i);
// Get the inner "data" array
JSONArray dataInner = jObject1.getJSONArray("data");
// Iterate the inner "data" array
for (int j = 0; j < dataInner.length() ; j++ ) {
JSONObject jItem = dataInner.getJSONObject(i);
String shopToken = jItem.getString("shopToken");
// parse the rest of the items
}
}
You can use Gson util to parse json whatever you want .
Map<String, List<ErrorInfo>> map = new HashMap<>();
map.put("ErrorInfos", list);
Gson gson = new Gson();
String json = gson.toJson(map);
Log.i("response", json);
And my json str is :
{"ErrorInfos":[{"errorDetails":"Connect time out"},{"errorDetails":"Connect time out"}]}
You can use jackson libraries to parse json.
Eg:-
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
Refer:http://www.tutorialspoint.com/jackson/
http://www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial.
I have created an Api which is used to add multiple invitations in the database called as sendMultipleInvites.
Now I want to implement this API in android. I am trying to create an AsyncTask to call the api. I have helper class to connect to http server.
I am testing this in postman: my input should be like this:
{
"invitations": [
{
"date" : "12/08/2016",
"invitee_no" : "196756456",
"status" : "1",
"user_name" : "user10"
},
{
"date" : "12/08/2016",
"invitee_no" : "13633469",
"status" : "1",
"user_id" : "user9"
}
]
}
My serverRequest class:
public class ServerRequest {
String api;
JSONObject jsonParams;
public ServerRequest(String api, JSONObject jsonParams) {
this.api = api;
this.jsonParams = jsonParams;
}
public JSONObject sendRequest() {
try {
URL url = new URL(api);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(jsonParams.toString());
writer.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while ( (line = reader.readLine()) != null ){
sb.append(line);
}
reader.close();
Log.d("ServerResponse", new String(sb));
return new JSONObject(new String(sb));
} else {
throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode);
}
} catch (MalformedURLException me) {
me.printStackTrace();
return Excpetion2JSON.getJSON(me);
} catch(IOException ioe) {
ioe.printStackTrace();
return Excpetion2JSON.getJSON(ioe);
} catch(UnexpectedServerException ue) {
ue.printStackTrace();
return Excpetion2JSON.getJSON(ue);
} catch (JSONException je) {
je.printStackTrace();
return Excpetion2JSON.getJSON(je);
}
}
public ServerRequest(String api) {
this.api = api;
}
}
This is my asyncTask :
public class SendMultipleInvitesAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject> {
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("status");
String message = jsonObject.getString("message");
if (result == 1) {
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Edit:
Trying like this it is giving an error when I try to pass an arraylist to the execute method of async task.
AsyncTask:
public class SendInviteAsyncTask extends AsyncTask<ArrayList<Invitation>, Void, JSONObject> {
private ProgressDialog progressDialog;
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(ArrayList<Invitation>... arrayLists) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
Activity:
public class SendMultipleInvites extends AppCompatActivity {
private ArrayList<Invitation> invitationArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_multiple_invites);
invitationArrayList = new ArrayList<>();
Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");
invitationArrayList.add(invitation);
invitation = new Invitation("3","17/02/2016","282751221","1","user10");
invitationArrayList.add(invitation);
new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(invitationArrayList);
}
}
I was using hash map to send key and values. How can I do to send a json array?
How to modify my async Task? How can I send array to an async task? Can anyone help please.. Thank you..
To pass Array to your async Task do this:
SendInviteAsyncTask extends AsyncTask<ArrayList<Sring>, Void, JSONObject>
To make a Json object you can use Gson library
try this
JSONObject obj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject()
reqObj.put( "ctrlId", "txt1" );
req.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "ctrlId", "txt2" );
req.put( reqObj );
obj.put( "req", req );
You can really simplify your code by using a few libraries for building json and sending http requests. Here is sample code using Gson for building the json string and Volley for the http request.
I also used this fantastic project for generating the json pojo objects below. It makes really quick work of it.
Invite ivt = new Invite();
ivt.getInvitations().add( new Invitation("3","17/02/2016","55165122","1","user10"));
ivt.getInvitations().add( new Invitation("3","17/02/2016","282751221","1","user10"));
Gson gson = new Gson();
String jsonString = gson.toJson(ivt);
String url = appContext.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
RequestQueue queue = Volley.newRequestQueue(appContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("TAG", "success: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
Invite.java
public class Invite {
#SerializedName("invitations")
#Expose
private List<Invitation> invitations = new ArrayList<Invitation>();
public List<Invitation> getInvitations() {
return invitations;
}
public void setInvitations(List<Invitation> invitations) {
this.invitations = invitations;
}
}
Invitation.java
public class Invitation {
#SerializedName("date")
#Expose
private String date;
#SerializedName("invitee_no")
#Expose
private String inviteeNo;
#SerializedName("status")
#Expose
private String status;
#SerializedName("user_name")
#Expose
private String userName;
#SerializedName("user_id")
#Expose
private String userId;
public Invitation(String d, String one, String two, String three, String four) {
date = d;
inviteeNo = one;
status = two;
userName = three;
userId = four;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInviteeNo() {
return inviteeNo;
}
public void setInviteeNo(String inviteeNo) {
this.inviteeNo = inviteeNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}