Android 在recyclerview中解析json格式的Rest api而不使用数组名
在我的应用程序中,我实现了recyclerview。此recyclerview将填充json数据。这个json数据将来自RESTAPI。现在,我正在尝试使用HttpUrlConnection获取此数据。到目前为止,我已经通过阅读网站上的一些文章实现了这段代码。但我在recyclerview中没有得到任何数据,所以在logcat上没有得到响应。我在Stackoverflow上读过类似的帖子。但是没有什么能解决我的问题。下面是我对api的json响应 Api响应Android 在recyclerview中解析json格式的Rest api而不使用数组名,android,json,rest,android-recyclerview,httpurlconnection,Android,Json,Rest,Android Recyclerview,Httpurlconnection,在我的应用程序中,我实现了recyclerview。此recyclerview将填充json数据。这个json数据将来自RESTAPI。现在,我正在尝试使用HttpUrlConnection获取此数据。到目前为止,我已经通过阅读网站上的一些文章实现了这段代码。但我在recyclerview中没有得到任何数据,所以在logcat上没有得到响应。我在Stackoverflow上读过类似的帖子。但是没有什么能解决我的问题。下面是我对api的json响应 Api响应 [ { "_id": "595bdc
[
{
"_id": "595bdcf32c67a3f9ee6c2a21",
"dn": "ferwetrert",
"whenChanged": "20170704065349.0Z",
"name": "Student",
"mail": "student@mail.com",
"updated_at": "2017-07-04T18:22:43.624Z"
},
{
"_id": "595bdcf32c67a3f9ee6c2a25",
"dn": "CN=Accounting,OU=users,OU=bluERP,OU=companies,DC=blu,DC=local",
"givenName": "given name",
"whenChanged": "20170801114732.0Z",
"name": "Accounting",
"mail": "accounting@mail.com",
"updated_at": "2017-07-04T18:22:43.641Z"
},
{
"_id": "590321138",
"dn": "CN=hallo name,OU=emplyee,OU=Organisation,DC=com,DC=local",
"sn": "",
"title": "developer",
"givenName": "Tina",
"whenChanged": "20170809073930.0Z",
"department": "Mobile",
"company": "Private limited",
"name": "Full Name",
"mail": "mail@yahoo.com",
"mobile": "+123456",
"updated_at": "2017-04-28T11:01:39.475Z"
}
]
我的模型课是
public class ColleagueModel {
private String id;
private String dn;
private String sn;
private String givenName;
private String whenChanged;
private String name;
private String mail;
private String updatedAt;
private String title;
private String department;
private String company;
private String mobile;
public ColleagueModel(){
}
public ColleagueModel(){
}
public ColleagueModel(String name, String company,String title) {
this.name = name;
this.company = company;
this.title = title;
}
我的活动课是
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String>{
HttpURLConnection conn;
URL url = null;
@Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://app.../api/users");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
List<ColleagueModel> data=new ArrayList<>();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
ColleagueModel model = new ColleagueModel();
String val1=json_data.optString("name");
String val2= json_data.optString("company");
String val3=json_data.optString("title");
model = new ColleagueModel(val1,val2,val3);
data.add(model);
}
// Setup and Handover data to recyclerview
recyclerView = findViewById(R.id.colleagues_recycler);
adapter = new MyColleaguesAdapter(MyColleaguesPage.this, data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
} catch (JSONException e) {
Toast.makeText(MyColleaguesPage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
像这样替换java文件。
公共类MyColleaguesPage扩展AppCompatActivity实现MyColleAgueAdapter.ColleAgueListener{
//连接超时和读取超时以毫秒为单位
公共静态最终int连接\u超时=10000;
公共静态最终整型读取超时=15000;
私人回收站;
专用MyColleAgueAdapter适配器;
列表数据=新的ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_布局);
recyclerView=findViewById(R.id.U回收商);
recyclerView.setLayoutManager(新的LinearLayoutManager(MyColleaguesPage.this));
adapter=新的MyColleaguesAdapter(MyColleaguesPage.this,data);
recyclerView.setAdapter(适配器);
新建AsyncFetch().execute();
}
私有类AsyncFetch扩展了AsyncTask{
httpurl连接连接;
URL=null;
@凌驾
受保护的字符串背景(字符串…字符串){
试一试{
//输入json文件所在的URL地址
//甚至可以调用返回json数据的php文件
url=新url(“https://app.../api/users");
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
返回e.toString();
}
试一试{
//设置HttpURLConnection类以从php和mysql发送和接收数据
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(读取超时);
连接设置连接超时(连接超时);
conn.setRequestMethod(“GET”);
//当我们从json文件接收数据时,将setDoOutput设置为true
连接设置输出(真);
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
返回e1.toString();
}
试一试{
int response_code=conn.getResponseCode();
//检查连接是否成功
if(response\u code==HttpURLConnection.HTTP\u OK){
//读取从服务器发送的数据
InputStream input=conn.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(输入));
StringBuilder结果=新建StringBuilder();
弦线;
而((line=reader.readLine())!=null){
结果。追加(行);
}
//将数据传递给onPostExecute方法
返回(result.toString());
}否则{
返回(“未成功”);
}
}捕获(IOE异常){
e、 printStackTrace();
返回e.toString();
}最后{
连接断开();
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
//此方法将在UI线程上运行
试一试{
JSONArray jArray=新JSONArray(结果);
//从json中提取数据并作为类对象存储到ArrayList中
对于(int i=0;i我认为您应该使用截击,一切都会很简单Gson最好处理json字符串转换
这是您的代码
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<ColleagueModel> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
recyclerView = findViewById(R.id.colleagues_recycler);
adapter = new MyColleaguesAdapter(MyColleaguesPage.this, data);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
recyclerView.setAdapter(adapter);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
@Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://app.../api/users");
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
Type modelList = new TypeToken<List<ColleagueModel>>() {
}.getType();
List<ColleagueModel> CollegeagueList = new Gson().fromJson(result, modelList);
data = CollegeagueList;
adapter.notifyDatasetChanged();
}
}
}
如果您在手动Http连接中遇到更多问题,您可以
通过改进开源库来实现它
如果您想知道如何在项目中实施改造,请参阅
本教程
使用以下链接简单解释如何将数据附加到回收器视图。
您是否尝试在日志中打印数据值?@shahid17june是的,我试图获取val1,但没有数据。我已附上我的日志。logcatLog.d中String result
的onPostExecute
内的值是多少(“结果”+,String.valueOf(jArray));我尝试这样做。但我在这里没有得到任何答复。它直接转到OnPostExecution中的异常尝试打印Log.d(“result”,result);和检查之前我尝试用库来做。但是我对android开发非常陌生。所以有很多事情我不能用库来处理。我试过你的代码。但它从来没有在onpostexecution中执行尝试。我从异常中得到消息,java.lang.string无法与java Array协调。我刚刚通知我没有得到消息正在删除服务器的任何响应。它正在返回(“不成功”);并转到on post exception中的异常。在服务器上发送正确的请求时是否有任何错误请参阅最后一行。您可以使用改型来处理网络呼叫。我已尝试过改型。以前。您是否可以查看此帖子
Replace Your java file like this.
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
List<ColleagueModel> data=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
recyclerView = findViewById(R.id.colleagues_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
adapter = new MyColleaguesAdapter(MyColleaguesPage.this, data);
recyclerView.setAdapter(adapter);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String>{
HttpURLConnection conn;
URL url = null;
@Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://app.../api/users");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
ColleagueModel model = new ColleagueModel();
String val1=json_data.optString("name");
String val2= json_data.optString("company");
String val3=json_data.optString("title");
model = new ColleagueModel(val1,val2,val3);
data.add(model);
}
// notify recyclerview
adapter.notifyDataSetChanged();
} catch (JSONException e) {
Toast.makeText(MyColleaguesPage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<ColleagueModel> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
recyclerView = findViewById(R.id.colleagues_recycler);
adapter = new MyColleaguesAdapter(MyColleaguesPage.this, data);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
recyclerView.setAdapter(adapter);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
@Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://app.../api/users");
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
Type modelList = new TypeToken<List<ColleagueModel>>() {
}.getType();
List<ColleagueModel> CollegeagueList = new Gson().fromJson(result, modelList);
data = CollegeagueList;
adapter.notifyDatasetChanged();
}
}
}
compile 'com.google.code.gson:gson:2.8.1'