- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试解析来自 https://newsapi.org
的 JSON
数据并将其显示在应用程序中的 recyclerview
上。下面给出了 JSON
数据的示例:
{
"status": "ok",
"totalResults": 10,
"articles": [
{
"source": {
"id": "google-news",
"name": "Google News"
},
"author": "Kanga Kong",
"title": "Kim Jong Un Sends Right-Hand Man to U.S. for Pre-Summit Talks",
"description": "North Korean leader Kim Jong Un has dispatched one of his top aides to the U.S. for talks ahead of his planned summit with Donald Trump next month, according to a person familiar with the issue who asked not to be named because the trip isn’t public.",
"url": "https://www.bloomberg.com/news/articles/2018-05-29/kim-jong-un-sends-aide-to-u-s-for-pre-summit-talks-yonhap-says",
"urlToImage": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/i7_b0Umv.ads/v0/1200x802.jpg",
"publishedAt": "2018-05-29T05:42:00+00:00"
},
问题是我无法从给定的 JSON
数据中获取任何数据。代码如下:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
private List<Model> modelList;
private RecyclerView recyclerView;
private CustomAdapter customAdapter;
String url="https://newsapi.org/v2/top-headlines?sources=google-news&apiKey=76351c3c06504e12a8c61428162dcf87";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=(RecyclerView)findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
customAdapter=new CustomAdapter(MainActivity.this,modelList);
recyclerView.setAdapter(customAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
new DownloadTask().execute(url);
}
public class DownloadTask extends AsyncTask<String,Void,String> {
private ProgressDialog progressDialog=new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... strings) {
String result=null;
StringBuilder response = null;
//Integer result=0;
try {
HttpsURLConnection urlConnection;
try {
URL url=new URL(strings[0]);
urlConnection=(HttpsURLConnection)url.openConnection();
int statusCode=urlConnection.getResponseCode();
if (statusCode==HttpsURLConnection.HTTP_OK){
BufferedReader br=new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
response=new StringBuilder();
String line;
while ((line=br.readLine()) !=null) {
response.append(line);
}
parseResult(response.toString());
//result=1;
} /*else {
result=0;
}*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (final Exception e){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Error",Toast.LENGTH_LONG).show();
}
});
}
Log.d("ResultForParsing : ",String.valueOf(result));
Log.d("ResponseForParsing : ",response.toString());
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject mJsonResponse;
try {
if (progressDialog!=null)
progressDialog.dismiss();
} catch (Exception e){
e.printStackTrace();
}
/*if (integer==1){
customAdapter=new CustomAdapter(MainActivity.this,modelList);
recyclerView.setAdapter(customAdapter);
} else {
Toast.makeText(getApplicationContext(),"Failed to fetch data",
Toast.LENGTH_LONG).show();
}*/
parseResult(result);
}
}
private void parseResult(String result){
try {
JSONArray posts=new JSONArray(result);
modelList=new ArrayList<>();
for (int i=0;i<posts.length();i++){
JSONObject post=posts.optJSONObject(i);
Model item=new Model();
item.setAuthor(post.optString("author"));
item.setTitle(post.optString("title"));
item.setDescription(post.optString("description"));
modelList.add(item);
Log.d("AuthorForJSON : ",post.optString("author"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这里,我使用了Log
语句来显示连接是否正常,它返回1,表示连接建立成功。
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<Model> model;
public CustomAdapter(Context context, List<Model> model) {
this.context = context;
this.model = model;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//View view=inflater.inflate(R.layout.row,null);
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//ViewHolder viewHolder=(ViewHolder)holder;
Model current=model.get(position);
holder.n_author.setText("Author : "+current.author);
holder.n_description.setText(current.description);
holder.n_title.setText(current.title);
//Picasso.get().load(current.urltoimage).into(n_image);
}
@Override
public int getItemCount() {
return (null!=model?model.size():0);
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView n_title;
TextView n_author;
ImageView n_image;
TextView n_description;
public ViewHolder(View itemView) {
super(itemView);
n_title=(TextView)itemView.findViewById(R.id.news_title);
n_author=(TextView)itemView.findViewById(R.id.news_author);
n_image=(ImageView)itemView.findViewById(R.id.news_image);
n_description=(TextView) itemView.findViewById(R.id.news_description);
}
}
}
模型.java
public class Model {
public String author;
public String title;
public String description;
public String url;
public String urltoimage;
public String published;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrltoimage() {
return urltoimage;
}
public void setUrltoimage(String urltoimage) {
this.urltoimage = urltoimage;
}
public String getPublished() {
return published;
}
public void setPublished(String published) {
this.published = published;
}
}
目前我只对获取作者
姓名、标题
和描述
感兴趣。
Logcat
05-29 12:59:15.052 9368-9528/com.example.pritom14.saveeverything I/System.out: [OkHttp] sendRequest<<
05-29 12:59:15.052 9368-9528/com.example.pritom14.saveeverything D/NativeCrypto: ssl=0x7fa58d2780 sslWrite buf=0x7f8f8e8000 len=240 write_timeout_millis=0
ssl=0x7fa58d2780 sslRead buf=0x7f8f8e8000 len=2048,timeo=0
05-29 12:59:15.377 9368-9528/com.example.pritom14.saveeverything D/NativeCrypto: ssl=0x7fa58d2780 sslRead buf=0x7f8f8e8000 len=2048,timeo=0
05-29 12:59:15.378 9368-9528/com.example.pritom14.saveeverything D/NativeCrypto: ssl=0x7fa58d2780 sslRead buf=0x7f8f8e8000 len=2048,timeo=0
05-29 12:59:15.379 9368-9528/com.example.pritom14.saveeverything D/NativeCrypto: ssl=0x7fa58d2780 sslRead buf=0x7f8f8e8000 len=2048,timeo=0
05-29 12:59:15.394 9368-9528/com.example.pritom14.saveeverything W/System.err: org.json.JSONException: Value {"status":"ok","totalResults":10,"articles":[{"source":{"id":"google-news","name":"Google News"},"author":"https:\/\/www.facebook.com\/bbcnews","title":"Private search for MH370 formally ends","description":"The Malaysia Airlines plane with 239 people disappeared while flying to Beijing from Kuala Lumpur.","url":"http:\/\/www.bbc.com\/news\/world-asia-44285241","urlToImage":"https:\/\/ichef.bbci.co.uk\/news\/1024\/branded_news\/E54A\/production\/_101789685_mediaitem101789684.jpg","publishedAt":"2018-05-29T05:17:22+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":"Analysis by Stephen Collinson, CNN","title":"Trump whips up immigration storm over children","description":"For President Donald Trump, every crisis in America's immigration system is an opportunity.","url":"https:\/\/www.cnn.com\/2018\/05\/29\/politics\/donald-trump-immigration-separated-children\/index.html","urlToImage":"https:\/\/cdn.cnn.com\/cnnnext\/dam\/assets\/180523143703-02-trump-immigration-rountable-05-23-2018-super-tease.jpg","publishedAt":"2018-05-29T05:02:57+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":null,"title":"The Rockets' heartbreaking failure to launch","description":"Houston's stars thrived, Clint Capela emerged and all the pieces fell into place. But in the end, the Warriors and an untimely CP3 injury proved too much to overcome.","url":"http:\/\/www.espn.com\/nba\/story\/_\/id\/23634056\/the-houston-rockets-heartbreaking-failure-launch-nba","urlToImage":"http:\/\/a2.espncdn.com\/combiner\/i?img=%2Fphoto%2F2018%2F0528%2Fr377007_1296x729_16%2D9.jpg","publishedAt":"2018-05-29T04:44:35+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":"Vivian Salama","title":"White House Halts New North Korea Sanctions in Mad Dash to Save Summit","description":"The U.S. decided to defer launching a major new sanctions push against North Korea, part of a flurry of weekend moves by both sides aimed at reviving a summit between President Trump and North Korea’s Kim Jong Un.","url":"https:\/\/www.wsj.com\/articles\/nations-race-to-save-korea-summit-1527547115","urlToImage":"https:\/\/images.wsj.net\/im-12257\/social","publishedAt":"2018-05-29T03:44:58+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":"https:\/\/www.nytimes.com\/by\/matt-stevens","title":"TV Journalists Covering Storm Are Killed When Tree Crushes S.U.V. in North Carolina","description":"The news anchor and photojournalist for WYFF News 4 in Greenville, S.C., had been reporting on the effects of Subtropical Storm Alberto.","url":"https:\/\/www.nytimes.com\/2018\/05\/28\/us\/tv-news-crew-killed-falling-tree.html","urlToImage":"https:\/\/static01.nyt.com\/images\/2018\/05\/29\/us\/29WYFF\/29WYFF-facebookJumbo.jpg","publishedAt":"2018-05-29T03:13:51+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":"Erik Ortiz, Tim Stelloh, Associated Press, Mary Murray, Matthew Vann","title":"Two journalists killed as Alberto makes landfall on Florida Panhandle","description":"Two journalists for NBC affiliate WYFF of Greenville, South Carolina, were killed when a tree fell on their car in North Carolina after Alberto made landfall.","url":"https:\/\/www.nbcnews.com\/news\/us-news\/storm-alberto-nearing-landfall-along-florida-panhandle-threatens-heavy-rains-n878021","urlToImage":"https:\/\/media3.s-nbcnews.com\/j\/newscms\/2018_22\/2446921\/180528-storm-alberto-florida-1059a-rs_356711a28e00435f2979771b572648ba.1200;630;7;70;5.JPG","publishedAt":"2018-05-29T02:32:29+00:00"},{"source":{"id":"google-news","name":"Google News"},"author":"Laurel Wamsley","title":"On Memorial Day, Trump Honors Fallen Soldiers; Draws Criticism Over Tweet","description":"\"They fought and bled and died so that America would forever remain safe and strong and free,\" Trump said at Arlington cemetery. Earlier, he drew criticism online for praise some found self-serving.","url":"https:\/\/www.npr.org\/sections\/thetwo-way\/2018\/05\/28\/614993465\/on-memorial-day-trump-honors-fal
05-29 12:59:15.395 9368-9528/com.example.pritom14.saveeverything W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
05-29 12:59:15.398 9368-9528/com.example.pritom14.saveeverything W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
05-29 12:59:15.399 9368-9528/com.example.pritom14.saveeverything W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.pritom14.saveeverything.MainActivity.parseResult(MainActivity.java:109)
at com.example.pritom14.saveeverything.MainActivity.access$000(MainActivity.java:28)
05-29 12:59:15.400 9368-9528/com.example.pritom14.saveeverything W/System.err: at com.example.pritom14.saveeverything.MainActivity$DownloadTask.doInBackground(MainActivity.java:78)
at com.example.pritom14.saveeverything.MainActivity$DownloadTask.doInBackground(MainActivity.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
05-29 12:59:15.401 9368-9528/com.example.pritom14.saveeverything W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
05-29 12:59:15.401 9368-9528/com.example.pritom14.saveeverything D/ResultForParsing :: null
05-29 14:54:04.099 16044-16149/com.example.pritom14.saveeverything D/ResponseForParsing :: {"status":"ok","totalResults":10,"articles":[{"source":{"id":"google-news","name":"Google News"},"author".....
有人可以帮我吗?
谢谢
最佳答案
尝试一下,它肯定会起作用,因为您在结果参数中获取了 json 对象。
private void parseResult(String result) {
Log.e("result::>", result);
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.getString("status").equalsIgnoreCase("ok")) {
JSONArray jsonArray = jsonObject.getJSONArray("articles");
modelList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject post = jsonArray.optJSONObject(i);
Model item = new Model();
item.setAuthor(post.optString("author"));
item.setTitle(post.optString("title"));
item.setDescription(post.optString("description"));
modelList.add(item);
Log.d("AuthorForJSON : ", post.optString("author"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
希望有帮助。
关于java - 解析 JSON 数据时不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50578651/
我一直在使用 AJAX 从我正在创建的网络服务中解析 JSON 数组时遇到问题。我的前端是一个简单的 ajax 和 jquery 组合,用于显示从我正在创建的网络服务返回的结果。 尽管知道我的数据库查
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我在尝试运行 Android 应用程序时遇到问题并收到以下错误 java.lang.NoClassDefFoundError: com.parse.Parse 当我尝试运行该应用时。 最佳答案 在这
有什么办法可以防止etree在解析HTML内容时解析HTML实体吗? html = etree.HTML('&') html.find('.//body').text 这给了我 '&' 但我想
我有一个有点疯狂的例子,但对于那些 JavaScript 函数作用域专家来说,它看起来是一个很好的练习: (function (global) { // our module number one
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 8 年前。 Improve th
我需要编写一个脚本来获取链接并解析链接页面的 HTML 以提取标题和其他一些数据,例如可能是简短的描述,就像您链接到 Facebook 上的内容一样。 当用户向站点添加链接时将调用它,因此在客户端启动
在 VS Code 中本地开发时,包解析为 C:/Users//AppData/Local/Microsoft/TypeScript/3.5/node_modules/@types//index而不是
我在将 json 从 php 解析为 javascript 时遇到问题 这是我的示例代码: //function MethodAjax = function (wsFile, param) {
我在将 json 从 php 解析为 javascript 时遇到问题 这是我的示例代码: //function MethodAjax = function (wsFile, param) {
我被赋予了将一种语言“翻译”成另一种语言的工作。对于使用正则表达式的简单逐行方法来说,源代码过于灵活(复杂)。我在哪里可以了解更多关于词法分析和解析器的信息? 最佳答案 如果你想对这个主题产生“情绪化
您好,我在解析此文本时遇到问题 { { { {[system1];1;1;0.612509325}; {[system2];1;
我正在为 adobe after effects 在 extendscript 中编写一些代码,最终变成了 javascript。 我有一个数组,我想只搜索单词“assemble”并返回整个 jc3_
我有这段代码: $(document).ready(function() { // }); 问题:FB_RequireFeatures block 外部的代码先于其内部的代码执行。因此 who
背景: netcore项目中有些服务是在通过中间件来通信的,比如orleans组件。它里面服务和客户端会指定网关和端口,我们只需要开放客户端给外界,服务端关闭端口。相当于去掉host,这样省掉了些
1.首先贴上我试验成功的代码 复制代码 代码如下: protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
什么是 XML? XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。 你可以通过本站学习 X
【PHP代码】 复制代码 代码如下: $stmt = mssql_init('P__Global_Test', $conn) or die("initialize sto
在SQL查询分析器执行以下代码就可以了。 复制代码代码如下: declare @t varchar(255),@c varchar(255) declare table_cursor curs
前言 最近练习了一些前端算法题,现在做个总结,以下题目都是个人写法,并不是标准答案,如有错误欢迎指出,有对某道题有新的想法的友友也可以在评论区发表想法,互相学习🤭 题目 题目一: 二维数组中的
我是一名优秀的程序员,十分优秀!