XML解析与JSON解析
Posted 一典数据
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML解析与JSON解析相关的知识,希望对你有一定的参考价值。
致亲爱的你
忙碌的一天又要过去了,今天有没有收获满满呢?
01
XML解析和JSON解析的概念
JSON解析是近几年才流行的一种新的数据格式,它与XML非常相似,都是用来存储数据的,但JSON相对于XML来说,解析速度更快,占用空间更小。
02
举个例子
视频讲解之后会补给大家的!请耐心等待...
温馨提示:代码的部分用电脑查看会更加方便噢!
package com.example.weatherdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tvCity,tvWeather,tvTemp,tvWind,tvPm;
private ImageView ivLcon;
private Map<String,String>map;
private List<Map<String,String>>list;
private String temp,weather,name,pm,wind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
try {
//使用xml解析
// InputStream is = this.getResources().openRawResource(R.raw.weather1);
// List<WeatherInfo> weatherInfos = WeatherService.getInfosFromXML(is);
//使用json解析
InputStream is = this.getResources().openRawResource(R.raw.weather2);
List<WeatherInfo> weatherInfos = WeatherService.getInfosFromJson(is);
list = new ArrayList<Map<String,String>>();
for (WeatherInfo info:weatherInfos) {
map = new HashMap<String,String>();
map.put("temp",info.getTemp());
map.put("weather",info.getWeather());
map.put("name",info.getName());
map.put("pm",info.getPm());
map.put("wind",info.getWind());
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this,"解析失败",Toast.LENGTH_SHORT).show();
}
getMap(1,R.drawable.sun);
}
private void initView(){
tvCity=findViewById(R.id.tv_city);
tvWeather=findViewById(R.id.tv_weather);
tvTemp=findViewById(R.id.tv_temp);
tvWind=findViewById(R.id.tv_wind);
tvPm=findViewById(R.id.tv_pm);
ivLcon=findViewById(R.id.tv_icon);
findViewById(R.id.btn_sh).setOnClickListener(this);
findViewById(R.id.btn_bj).setOnClickListener(this);
findViewById(R.id.btn_gz).setOnClickListener(this);
}
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.btn_sh:
getMap(0,R.drawable.cloud_sun);
break;
case R.id.btn_bj:
getMap(1,R.drawable.sun);
break;
case R.id.btn_gz:
getMap(2,R.drawable.clouds);
break;
}
}
private void getMap(int number,int iconNumber){
Map<String,String> cityMap = list.get(number);
temp = cityMap.get("temp");
weather = cityMap.get("weather");
name = cityMap.get("name");
pm = cityMap.get("pm");
wind = cityMap.get("wind");
tvCity.setText(name);
tvWeather.setText(weather);
tvTemp.setText(""+ temp);
tvWind.setText("风力:"+wind);
tvPm.setText("pm: "+pm);
ivLcon.setImageResource(iconNumber);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/weather"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="@+id/tv_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上海"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="50dp"
android:textSize="50sp"/>
<ImageView
android:id="@+id/tv_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="@mipmap/ic_launcher"
android:layout_below="@+id/tv_city"
android:layout_alignLeft="@+id/tv_city"/>
<TextView
android:id="@+id/tv_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="多云"
android:layout_below="@+id/tv_icon"
android:layout_alignLeft="@+id/tv_icon"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignTop="@id/tv_icon"
android:layout_toRightOf="@id/tv_icon"
android:layout_marginLeft="40dp">
<TextView
android:id="@+id/tv_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-7C"
android:textSize="22sp"/>
<TextView
android:id="@+id/tv_wind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="风力3级"
android:textSize="18sp"/>
<TextView
android:id="@+id/tv_pm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pm"
android:textSize="18sp"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="@+id/btn_bj"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="北京"/>
<Button
android:id="@+id/btn_sh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上海"/>
<Button
android:id="@+id/btn_gz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="广州"/>
</LinearLayout>
</LinearLayout>
WeatherInfo.java
package com.example.weatherdemo;
public class WeatherInfo {
private String id;
private String temp;
private String weather;
private String name;
private String pm;
private String wind;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPm() {
return pm;
}
public void setPm(String pm) {
this.pm = pm;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
}
package com.example.weatherdemo;
import android.util.Xml;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.xmlpull.v1.XmlPullParser;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class WeatherService {
//解析XML文件返回天气信息的集合
public static List<WeatherInfo> getInfosFromXML(InputStream is)throws Exception{
List<WeatherInfo> weatherInfos = null;
WeatherInfo weatherInfo = null;
//解析XML文件,得到每一个weatherinfo
//采用PULL解析方式
//第一步得到pull解析器并初始化,第一个参数代表包含xml的数据源
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is,"utf-8");
//第二步,获得当前事件的类型
int type = parser.getEventType();
//END_DOCUMENT为文档结束标签
while (type!=XmlPullParser.END_DOCUMENT){
switch (type){
//一个节点的开始标签
case XmlPullParser.START_TAG:
if ("infos".equals(parser.getName())){
weatherInfos = new ArrayList<WeatherInfo>();
}else if ("city".equals(parser.getName())){
weatherInfo = new WeatherInfo();
String idStr = parser.getAttributeName(0);
weatherInfo.setId(idStr);
}else if ("temp".equals(parser.getName())){
//parser.nextText()可以得到节点tag中的内容
String temp = parser.nextText();
weatherInfo.setTemp(temp);
}else if ("weather".equals(parser.getName())){
String weather = parser.nextText();
weatherInfo.setWeather(weather);
}else if ("name".equals(parser.getName())){
String name = parser.nextText();
weatherInfo.setName(name);
}else if ("pm".equals(parser.getName())){
String pm = parser.nextText();
weatherInfo.setPm(pm);
}else if ("wind".equals(parser.getName())){
String wind = parser.nextText();
weatherInfo.setWind(wind);
}
break;
//一个节点的结束标签
case XmlPullParser.END_TAG:
//遇到city结束标签,说明一个城市的信息处理完毕
if ("city".equals(parser.getName())){
weatherInfos.add(weatherInfo);
weatherInfo=null;
}
break;
}
type = parser.next();
}
return weatherInfos;
}
//解析json文件返回天气信息的集合
public static List<WeatherInfo> getInfosFromJson(InputStream is) throws Exception{
List<WeatherInfo> weatherInfos = null;
//使用gson解析json数据
Gson gson = new Gson();
Type listType = new TypeToken<List<WeatherInfo>>(){}.getType();
byte[] buffer = new byte[is.available()];
is.read(buffer);
String json = new String(buffer,"utf-8");
//调用Gson的from方法解析json数据,返回的数据类型时List
weatherInfos=gson.fromJson(json,listType);
return weatherInfos;
}
}
<infos>
<city id="sh">
<temp>20℃/30℃</temp>
<weather>晴天多云</weather>
<name>上海</name>
<pm>80</pm>
<wind>1级</wind>
</city>
<city id="bj">
<temp>26℃/32℃</temp>
<weather>晴天</weather>
<name>北京</name>
<pm>98</pm>
<wind>3级</wind>
</city>
<city id="gz">
<temp>15℃/24℃</temp>
<weather>多云</weather>
<name>广州</name>
<pm>30</pm>
<wind>5级</wind>
</city>
</infos>
Weather2.json
[
{"temp":"20℃/30℃","weather":"晴转多云","name":"上海","pm":"80","wind":"1级"},
{"temp":"15℃/24℃","weather":"晴","name":"北京","pm":"98","wind":"3级"},
{"temp":"26℃/32℃","weather":"多云","name":"广州","pm":"30","wind":"2级"}
]
03
运行结果
与最亲爱的你
我们一起进步...
文字:露出马脚
扫码关注我吧!
以上是关于XML解析与JSON解析的主要内容,如果未能解决你的问题,请参考以下文章