Json和Xml解析

1.XML解析

package com.example.exercise3;

public class City {
    private  int id;
    private  String temp;
    private  String weather;
    private  String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private  String pm;
    private  String wind;

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

    @Override
    public String toString() {
        return
                "temp='" + temp + '\'' +
                ", pm='" + pm + '\'' +
                ", wind='" + wind + '\'';
    }
}

weather.xml

<?xml version="1.0" encoding="utf-8"?>
<infos>
    <city id="1">
        <temp>20℃/30℃</temp>
        <weather>晴天多云</weather>
        <name>上海</name>
        <pm>80</pm>
        <wind>1级</wind>
    </city>
    <city id="2">
        <temp>26℃/32℃</temp>
        <weather>晴天</weather>
        <name>北京</name>
        <pm>98</pm>
        <wind>3级</wind>
    </city>
    <city id="3">
        <temp>15℃/24℃</temp>
        <weather>多云</weather>
        <name>广州</name>
        <pm>30</pm>
        <wind>5级</wind>
    </city>
</infos>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/weather"
    tools:context=".XML">

   <TextView
       android:id="@+id/xml_city_name"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_margin="50dp"
       android:textSize="60dp" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/xml_weather_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
           />

        <TextView
            android:id="@+id/xml_weather_info"
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"/>

    </LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_marginTop="-80dp"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/xml_beijing"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="280dp"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:textSize="40dp"
        android:text="北京"/>
    <Button
        android:id="@+id/xml_shanghai"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="280dp"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:textSize="40dp"
        android:text="上海"/>
    <Button
        android:id="@+id/xml_guangzhou"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="280dp"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:textSize="40dp"
        android:text="广州"/>
   </LinearLayout>
</LinearLayout>
package com.example.exercise3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class XML extends AppCompatActivity implements View.OnClickListener {

    private TextView xml_city_name,xml_weaher_info;
    private Button xml_beijing,xml_shanghai,xml_guangzhou;
    private ImageView xml_weather_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xml);
        init();

    }

    private void init() {
        xml_city_name= findViewById(R.id.xml_city_name);
        xml_weaher_info=findViewById(R.id.xml_weather_info);
        xml_weather_img=findViewById(R.id.xml_weather_img);
        xml_beijing=(Button)findViewById(R.id.xml_beijing);
        xml_guangzhou=(Button)findViewById(R.id.xml_guangzhou);
        xml_shanghai=(Button)findViewById(R.id.xml_shanghai);

        xml_beijing.setOnClickListener(this);
        xml_guangzhou.setOnClickListener(this);
        xml_shanghai.setOnClickListener(this);
        xml_city_name.setText("北京");
        xml_weaher_info.setText("晴 26℃/32℃ 98 3级");
        xml_weather_img.setImageResource(R.drawable.sun);
    }

    @Override
    public void onClick(View view) {
    //XML关键代码
        InputStream xml=this.getClass().getClassLoader().getResourceAsStream("assets/weather.xml");
        List<City> cities=null;
        try{
            cities=CityService.getCitys(xml);
        }catch (IOException e)
        {
            e.printStackTrace();
        }catch (XmlPullParserException e)
        {
            e.printStackTrace();
        }
        switch (view.getId())
        {
            case R.id.xml_beijing:
                for(City city:cities)
                {
                    if(city.getId()==2)
                    {
                        xml_city_name.setText(city.getName());
                        xml_weaher_info.setText(city.toString());
                        xml_weather_img.setImageResource(R.drawable.sun);
                    }
                }
                break;
            case R.id.xml_shanghai:
                for(City city:cities)
                {
                    if(city.getId()==1)
                    {
                        xml_city_name.setText(city.getName());
                        xml_weaher_info.setText(city.toString());
                        xml_weather_img.setImageResource(R.drawable.cloud_sun);
                    }
                }
                Log.e(null,"test");
                break;
            case R.id.xml_guangzhou:
                for(City city:cities)
                {
                    if(city.getId()==3)
                    {
                        xml_city_name.setText(city.getName());
                        xml_weaher_info.setText(city.toString());
                        xml_weather_img.setImageResource(R.drawable.cloud_sun);
                    }
                }
                Log.e(null,"test");
                break;
            default:break;

        }
    }
}

解析City

package com.example.exercise3;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CityService {
    public static List<City> getCitys(InputStream xml) throws IOException, XmlPullParserException
    {
        List<City> citys=null;
        City city=null;
        XmlPullParser pullParser= Xml.newPullParser();
        try {
            pullParser.setInput(xml,"UTF-8");
            int event=pullParser.getEventType();
            while (event!=XmlPullParser.END_DOCUMENT)
            {
                switch (event)
                {
                    case  XmlPullParser.START_DOCUMENT:
                        citys=new ArrayList<City>();
                        break;
                    case  XmlPullParser.START_TAG:
                        if("city".equals(pullParser.getName()))
                        {
                            int id=new Integer(pullParser.getAttributeValue(0));
                            city=new City();
                            city.setId(id);
                        }
                        if("temp".equals(pullParser.getName()))
                        {
                            String temp=pullParser.nextText();
                            city.setTemp(temp);
                        }
                        if("weather".equals(pullParser.getName()))
                        {
                            String weather=pullParser.nextText();
                            city.setWeather(weather);
                        }
                        if("name".equals(pullParser.getName()))
                        {
                            String name=pullParser.nextText();
                            city.setName(name);
                        }
                        if("pm".equals(pullParser.getName()))
                        {
                            String pm=pullParser.nextText();
                            city.setPm(pm);
                        }
                        if("wind".equals(pullParser.getName()))
                        {
                            String wind=pullParser.nextText();
                            city.setWind(wind);
                        }
                        break;
                        case XmlPullParser.END_TAG:
                            if("city".equals(pullParser.getName()))
                            {
                                citys.add(city);
                                city=null;
                            }
                            break;
                }
                event=pullParser.next();
            }
        }catch (XmlPullParserException e)
        {
            e.printStackTrace();
        }
        return  citys;
    }

}

2.JSON解析

package com.example.exercise3;

import android.content.Context;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.LinkedList;

public class JSON extends AppCompatActivity implements View.OnClickListener {
    private TextView json_city_name,json_weaher_info;
    private Button json_beijing,json_shanghai,json_guangzhou;
    private ImageView json_weather_img;
    FileReader reader=null;
    LinkedList<City> cities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        init();
        ReadJson();
    }


//JSON关键代码
    **//这是一个方法,其中filename是放在assets中的本地JSON文件名
    public static String getJson(String fileName, Context context){
        //这个用来保存JSON格式字符串,字符缓冲流
        StringBuilder stringBuilder = new StringBuilder();
        AssetManager assetManager = context.getAssets();
        try{
            BufferedReader bf=new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line=bf.readLine())!=null){
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }**

    private LinkedList<City> ReadJson() {

        String result = getJson("weather.json",this);
        Type listType=new TypeToken<LinkedList<City>>(){}.getType();
        Gson gson=new Gson();
         cities=gson.fromJson(result,listType);
        for(City city:cities)
        {
            Log.e(null,city.toString());
        }
        return  cities;
    }


    private void init() {
        json_city_name= findViewById(R.id.json_city_name);
        json_weaher_info=findViewById(R.id.json_weather_info);
        json_weather_img=findViewById(R.id.json_weather_img);
        json_beijing=findViewById(R.id.json_beijing);
        json_guangzhou=findViewById(R.id.json_guangzhou);
        json_shanghai=findViewById(R.id.json_shanghai);

        json_beijing.setOnClickListener(this);
        json_guangzhou.setOnClickListener(this);
        json_shanghai.setOnClickListener(this);
        json_city_name.setText("北京");
        json_weaher_info.setText("晴 26℃/32℃ 98 3级");
        json_weather_img.setImageResource(R.drawable.sun);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.json_beijing:
                for(City city:cities)
                {
                    if(city.getId()==1)
                    {
                        json_city_name.setText(city.getName());
                        json_weaher_info.setText(city.toString());
                        json_weather_img.setImageResource(R.drawable.sun);
                    }
                }
                break;
            case R.id.json_shanghai:
                for(City city:cities)
                {
                    if(city.getId()==2)
                    {
                        json_city_name.setText(city.getName());
                        json_weaher_info.setText(city.toString());
                        json_weather_img.setImageResource(R.drawable.sun);
                    }
                }
                break;
            case R.id.json_guangzhou:
                for(City city:cities)
                {
                    if(city.getId()==3)
                    {
                        json_city_name.setText(city.getName());
                        json_weaher_info.setText(city.toString());
                        json_weather_img.setImageResource(R.drawable.sun);
                    }
                }
                break;
            default:break;

        }
    }
}

Json和Xml解析
JSON文件

[
  {"id":2,"temp":"20℃/30℃","weather":"晴转多云","name":"上海","pm":"80","wind":"1级"},
  {"id":1,"temp":"15℃/24℃","weather":"晴","name":"北京","pm":"98","wind":"3级"},
  {"id":3,"temp":"26℃/32℃","weather":"多云","name":"广州","pm":"30","wind":"2级"}
]

运行效果
Json和Xml解析