如何从android中的服务器检索以下json数据?

时间:2017-03-03 06:28:46

标签: android json get

如何从android中的服务器检索以下json数据?能指导我一个例子吗?如何从下面的URL获取UserRole?

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

6 个答案:

答案 0 :(得分:2)

以下是从服务器

中检索json数据的示例

将Gson库的这种依赖关系添加到App的gradle:

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

创建模型类

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

}

现在使用Gson库从服务器对上述模型的响应转换数据。(注意:在AsyncTask类的onPostExecute()中写下这些行)

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

        }
}

答案 1 :(得分:1)

你正在回复json数组。您可以从以下数组中获取详细信息:

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

答案 2 :(得分:1)

使用以下代码获取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);
            }
        }

使用以下方法解析数据:

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

从链接下面找到API调用代码:

How to use a web API from your Android app

答案 3 :(得分:1)

您可以使用OkHttp从服务器获取json数据并使用fastjson来解析数据。 将这些依赖项添加到App的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' 

然后1.创建一个模型类:

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.使用OkHttp获取json数据并使用fastjson解析数据。

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

答案 4 :(得分:0)

您可以查看http://www.androidhive.info/2012/01/android-json-parsing-tutorial/并尝试在下次开始新主题之前搜索更多内容!

答案 5 :(得分:0)

试试这个,

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

您的Android项目的应用模块的gradle依赖项:

 compile 'com.android.volley:volley:1.0.0'