user7651705
user7651705

Reputation:

how to retrieve below json data from server in android?

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

Upvotes: 2

Views: 8051

Answers (6)

Jack_Zhang
Jack_Zhang

Reputation: 11

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(); } }

Upvotes: 1

Piyush
Piyush

Reputation: 2609

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();
        }

Upvotes: 1

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){
            }

        }
}

Upvotes: 2

Chetan Joshi
Chetan Joshi

Reputation: 5711

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

Upvotes: 1

Komal12
Komal12

Reputation: 3348

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'

Upvotes: 0

F.Dindar
F.Dindar

Reputation: 52

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 !

Upvotes: -1

Related Questions