android serveridagi json ma'lumotlarini qanday olish mumkin?

android serveridagi json ma'lumotlarini qanday olish mumkin? Iltimos, menga namuna bilan yo'l-yo'riq bera olasizmi? UserRoleni quyidagi urldan qanday olish mumkin?

http://beta.json-generator.com/api/json/get/ 4y2NmxAYf

1
json ma'lumotlarini olish uchun Tarmoq Operatsiyasini amalga oshirishingiz mumkin.
qo'shib qo'ydi muallif Chetan Joshi, manba

6 javoblar

Serverdan json ma'lumotlarini olishning misoli

Gson kutubxonasining ushbu qo'shimchasini App gradusi bilan qo'shing:

compile 'com.google.code.gson:gson:2.4'

Model sinf yaratish

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

}

Endi serverning yuqoridagi modelga bo'lgan javobidan ma'lumotlarni aylantirish uchun Gson kutubxonasidan foydalaning (Eslatma: AsyncTask klassining onPostExecute() da ushbu qatorlarni yozing)

@Override
protected void onPostExecute(final Boolean success) {
    try {
         if (success) {
               if (responsecode == 200) {
                   //GSON responsedata
                   if(responsedata!=null) {
                       if (responsedata != "") {
                           List userlist = new ArrayList();
                           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){
            }

        }
}
2
qo'shib qo'ydi

Siz javoban json qatori olasiz. Quyidagi kabi qatorlardan ma'lumotlarni olishingiz mumkin:

try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i=0; i
1
qo'shib qo'ydi
Muammo nimada? Foydalanuvchi xatosi
qo'shib qo'ydi muallif Piyush, manba
Share log cat xatosi va usulingizni
qo'shib qo'ydi muallif Piyush, manba
Xristian, men kodni quyida ishlatib bo'lmaydi. kodimni to'g'rilang.
qo'shib qo'ydi muallif user7651705, manba
Xristian, yuqorida kod ishlatilgan, u ijro etilmaydi. Iltimos, kodni o'zgartiring. (yuqoridagi kodni "Faoliyat" usuliga joylashtirdim)
qo'shib qo'ydi muallif user7651705, manba
elektron pochtangizni men bilan bo'lisha olasizmi?
qo'shib qo'ydi muallif user7651705, manba
Sizga katta rahmat...
qo'shib qo'ydi muallif user7651705, manba

JsonRespone-ni olish uchun quyidagi kodni ishlating:

    class RetrieveFeedTask extends AsyncTask {

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

Quyidagi usul yordamida ma'lumotlaringizni ajrating:

 private void parseJsonData(String jsonResponse){
        try
        {
            JSONArray jsonArray = new JSONArray(jsonResponse);

            for(int i=0;i

Quyidagi API chaqiruv kodini topish Link:

Android ilovasidan veb-APIni qanday ishlatish kerak

1
qo'shib qo'ydi
siz setVisibility (ViSIBLE.GONE) dan foydalanishingiz mumkin;
qo'shib qo'ydi muallif Chetan Joshi, manba
menga yordam berganingiz uchun tashakkur ...
qo'shib qo'ydi muallif user7651705, manba
Xristian, men bitta sinfda 3 tugmachani yozdim va yana bir sinfda 3 tugmachasini qanday yashirish kerak?
qo'shib qo'ydi muallif user7651705, manba

Serverdan json ma'lumotlarini olish uchun OkHttp-dan foydalanishingiz mumkin va ma'lumotlarni tahlil qilish uchun fastjson-dan foydalanishingiz mumkin. Ushbu bog'liqliklar ilovaning build.gradle-ga qo'shing:

compile 'com.alibaba:fastjson:1.2.24' 
compile 'com.squareup.okhttp3:okhttp:3.6.0' 
compile 'com.squareup.okio:okio:1.11.0' 

Keyin 1.Madal sinf yaratish:

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. Ma'lumotlarni tekshirish uchun json ma'lumotlarini olish va ma'lumotlarni yozish uchun OkHttp ni ishlatish.

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 models = JSON.parseArray(text, JsonModel.class);
                //Do other things based on models
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
1
qo'shib qo'ydi

Buni ko'ring,

        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://beta.json-generator.com/api/json/get/4y2NmxAYf",
                new Response.Listener() {
                    @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);

Android loyihangizning ilova moduli uchun gradle bog'liqliklar:

 compile 'com.android.volley:volley:1.0.0'
0
qo'shib qo'ydi

http://www.androidhive.info veb-saytiga tashrif buyurishingiz mumkin./2012/01/android-json-parse-tutorial/ va keyingi safar yangi mavzu boshlashdan oldin ko'proq qo'ng'iroq qilishga harakat qiling!

0
qo'shib qo'ydi
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb