解析gson
Posted xiaxinxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析gson相关的知识,希望对你有一定的参考价值。
public class MainActivity extends AppCompatActivity {
String urldata="http://api.tianapi.com/huabian/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10";
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.lv);
mytask mk = new mytask();
mk.execute();
}
class mytask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
try {
URL url=new URL(urldata);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
if (urlConnection.getResponseCode()==200){
InputStream inputStream = urlConnection.getInputStream();
return steamstring(inputStream);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//执行网络任务之后的请求,,更新UI
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
GetData getData = gson.fromJson(s, GetData.class);
Myadapter myadapter = new Myadapter(MainActivity.this, getData.getNewslist());
lv.setAdapter(myadapter);
}
}
public String steamstring(InputStream inputStream ){
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String str;
try {
while((str=reader.readLine())!=null){
builder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
以上是关于解析gson的主要内容,如果未能解决你的问题,请参考以下文章