JSON 解析

一 、Google 的Gson

Gson类:解析json的最基础的工具类

JsonParser类:解析器来解析JSON到JsonElements的解析树
JsonElement类:一个类代表的JSON元素
JsonObject类:JSON对象类型
JsonArray类:JsonObject数组
TypeToken类:用于创建type,比如泛型List<?>

使用时,不需要引用,Google官方2008提供免费sdk

1.基本使用

Gson gson = new Gson();

String json = "{\"id\":\"2\",\"name\":\"Json技术\"}";
Book book = gson.fromJson(json, Book.class);

2.List、Set 基本使用

//将json转换成 

  ListList list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());

//将json转换成Set
Set set = gson.fromJson(json,new TypeToken<SET>() {}.getType());

public class Student {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

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

    public void setName(String name) {
        this.name = name;
    }


    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Gson gson0 = new Gson();
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
List list = gson0.fromJson(json, new TypeToken<List<Student>>() {
}.getType());
System.out.print(list.toString());

3.通过json对象直接操作json以及一些json的工具
a)格式化Json
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(json);
json = gson.toJson(je);
b)判断字符串是否是json,通过捕捉的异常来判断是否是json
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
boolean jsonFlag;
try {
new JsonParser().parse(str).getAsJsonObject();
jsonFlag = true;
} catch (Exception e) {
jsonFlag = false;
}
c)从json串中获取属性
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'id';
String propertyValue = "";
try {
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
propertyValue = jsonObj.get(propertyName).toString();
} catch (Exception e) {
propertyValue = null;
}
d)除去json中的某个属性
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'id';
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
json = jsonObj.toString();
e)向json中添加属性
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'desc';
Object propertyValue = "json各种技术的调研";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();
f)修改json中的属性
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'name';
Object propertyValue = "json各种技术的调研";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();
g)判断json中是否有属性
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'name';
boolean isContains = false ;
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
isContains = jsonObj.has(propertyName);
h)json中日期格式的处理
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Gson gson = builder.create();
然后使用gson对象进行json的处理,如果出现日期Date类的对象,就会按照设置的格式进行处理
i)json中对于Html的转义
Gson gson = new Gson();
这种对象默认对Html进行转义,如果不想转义使用下面的方法
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();

4.Gson 复杂解析例子

 
String gesons = "{\n" +
        "            \"reason\":\"成功的返回\",\n" +
        "                \"result\":{\n" +
        "            \"stat\":\"1\",\n" +
        "                    \"data\": [\n" +
        "            {\n" +
        "                \"title\":\"男有陈冠希,女有张静初,专业睡导演30年惨遭导演太太集体封杀\",\n" +
        "                    \"date\":\"2016-09-12 06:18\",\n" +
        "                    \"author_name\":\"分合晚歌\",\n" +
        "                    \"thumbnail_pic_s\":\n" +
        "                \"http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpm_03200403.jpeg\",\n" +
        "                        \"thumbnail_pic_s02\":\n" +
        "                \"http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpl_05500201.jpeg\",\n" +
        "                        \"thumbnail_pic_s03\":\n" +
        "                \"http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpl_05500201.jpeg\",\n" +
        "                        \"url\":\"http://mini.eastday.com/mobile/160912061828549.html?qid=juheshuju\",\n" +
        "                    \"uniquekey\":\"160912061828549\",\n" +
        "                    \"type\":\"头条\",\n" +
        "                    \"realtype\":\"娱乐\"\n" +
        "            },\n" +
        "            {\n" +
        "                \"title\":\"赵薇怎么又胖又老,和林心如比起来差这么多?\",\n" +
        "                    \"date\":\"2016-09-12 06:08\",\n" +
        "                    \"author_name\":\"最美Angelababy\",\n" +
        "                    \"thumbnail_pic_s\":\n" +
        "                \"http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpm_03200403.jpeg\",\n" +
        "                        \"thumbnail_pic_s02\":\n" +
        "                \"http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpl_05500201.jpeg\",\n" +
        "                        \"thumbnail_pic_s03\":\n" +
        "                \"http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpl_05500201.jpeg\",\n" +
        "                        \"url\":\"http://mini.eastday.com/mobile/160912060823513.html?qid=juheshuju\",\n" +
        "                    \"uniquekey\":\"160912060823513\",\n" +
        "                    \"type\":\"头条\",\n" +
        "                    \"realtype\":\"娱乐\"\n" +
        "            }]\n" +
        "        }\n" +
        "        }";
Gson gson = new Gson();
//根据NewsResult的封装实体类进行解析
NewsResult newsResult = gson.fromJson(gesons, NewsResult.class);
//创建集合
List<NewsItem> newsItems = new ArrayList();
//将解析后的数据赋值给集合,以实现其他类的调用
newsItems = newsResult.getResult().getData();
System.out.println(newsItems.toString());
//获取每条详情
NewsItem newsItem = newsItems.get(0);
System.out.println(newsItem.toString());
public class News {

    private String stat;
    private List<NewsItem> data;


    public String getStat() {
        return stat;
    }

    public void setStat(String stat) {
        this.stat = stat;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    public News(String stat, List data) {
        super();
        this.stat = stat;
        this.data = data;
    }

}
public class NewsResult {
   
   private News result;

   public News getResult() {
      return result;
   }

   public void setResult(News result) {
      this.result = result;
   }

   @Override
   public String toString() {
      return "NewsResult [result=" + result + "]";
   }
}
public class NewsItem {
    private String title;
    private String date;
    private String author_name;
    private String thumbnail_pic_s;
    private String thumbnail_pic_s02;
    private String thumbnail_pic_s03;
    private String url;
    private long uniquekey;
    private String type;
    private String realtype;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getAuthor_name() {
        return author_name;
    }

    public void setAuthor_name(String author_name) {
        this.author_name = author_name;
    }

    public String getThumbnail_pic_s() {
        return thumbnail_pic_s;
    }

    public void setThumbnail_pic_s(String thumbnail_pic_s) {
        this.thumbnail_pic_s = thumbnail_pic_s;
    }

    public String getThumbnail_pic_s02() {
        return thumbnail_pic_s02;
    }

    public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
        this.thumbnail_pic_s02 = thumbnail_pic_s02;
    }

    public String getThumbnail_pic_s03() {
        return thumbnail_pic_s03;
    }

    public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
        this.thumbnail_pic_s03 = thumbnail_pic_s03;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public long getUniquekey() {
        return uniquekey;
    }

    public void setUniquekey(long uniquekey) {
        this.uniquekey = uniquekey;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getRealtype() {
        return realtype;
    }

    public void setRealtype(String realtype) {
        this.realtype = realtype;
    }

    @Override
    public String toString() {
        return "NewsItem [title=" + title + ", date=" + date + ", author_name="
                + author_name + ", thumbnail_pic_s=" + thumbnail_pic_s
                + ", thumbnail_pic_s02=" + thumbnail_pic_s02
                + ", thumbnail_pic_s03=" + thumbnail_pic_s03 + ", url=" + url
                + ", uniquekey=" + uniquekey + ", type=" + type + ", realtype="
                + realtype + "]";
    }

}

在复杂点Gson 解析


String geson2 = "{\n" +
        "    \"error\": 0,\n" +
        "    \"status\": \"success\",\n" +
        "    \"date\": \"2014-05-10\",\n" +
        "    \"results\": [\n" +
        "        {\n" +
        "            \"currentCity\": \"南京\",\n" +
        "            \"weather_data\": [\n" +
        "                {\n" +
        "                    \"date\": \"周六(今天, 实时:19℃)\",\n" +
        "                    \"dayPictureUrl\": \"http://api.map.baidu.com/images/weather/day/dayu.png\",\n" +
        "                    \"nightPictureUrl\": \"http://api.map.baidu.com/images/weather/night/dayu.png\",\n" +
        "                    \"weather\": \"大雨\",\n" +
        "                    \"wind\": \"东南风5-6级\",\n" +
        "                    \"temperature\": \"18℃\"\n" +
        "                },\n" +
        "                {\n" +
        "                    \"date\": \"周日\",\n" +
        "                    \"dayPictureUrl\": \"http://api.map.baidu.com/images/weather/day/zhenyu.png\",\n" +
        "                    \"nightPictureUrl\": \"http://api.map.baidu.com/images/weather/night/duoyun.png\",\n" +
        "                    \"weather\": \"阵雨转多云\",\n" +
        "                    \"wind\": \"西北风4-5级\",\n" +
        "                    \"temperature\": \"21 ~ 14℃\"\n" +
        "                }\n" +
        "            ]\n" +
        "        },\n" +
        "        {\n" +
        "            \"currentCity\": \"北京\",\n" +
        "            \"weather_data\": [\n" +
        "                {\n" +
        "                    \"date\": \"周六(今天, 实时:19℃)\",\n" +
        "                    \"dayPictureUrl\": \"http://api.map.baidu.com/images/weather/day/dayu.png\",\n" +
        "                    \"nightPictureUrl\": \"http://api.map.baidu.com/images/weather/night/dayu.png\",\n" +
        "                    \"weather\": \"大雨\",\n" +
        "                    \"wind\": \"东南风5-6级\",\n" +
        "                    \"temperature\": \"18℃\"\n" +
        "                },\n" +
        "                {\n" +
        "                    \"date\": \"周日\",\n" +
        "                    \"dayPictureUrl\": \"http://api.map.baidu.com/images/weather/day/zhenyu.png\",\n" +
        "                    \"nightPictureUrl\": \"http://api.map.baidu.com/images/weather/night/duoyun.png\",\n" +
        "                    \"weather\": \"阵雨转多云\",\n" +
        "                    \"wind\": \"西北风4-5级\",\n" +
        "                    \"temperature\": \"21 ~ 14℃\"\n" +
        "                }\n" +
        "            ]\n" +
        "        }\n" +
        "    ]\n" +
        "}\n";


Gson gson1 = new Gson();
WeatherResult weatherResult = gson.fromJson(geson2, WeatherResult.class);
List<Results> result0 = new ArrayList();
result0 = weatherResult.getResults();
List<Weather> result = new ArrayList();
//直接获取第一个Results
result = weatherResult.getResults().get(0).getWeather_data();
System.out.println(weatherResult.getStatus() + "\n" + result0.toString() + "\n" + result.toString() + "\n" + result.get(0).toString());
public class Results {
    private String currentCity;
    private List<Weather> weather_data;

    public String getCurrentCity() {
        return currentCity;
    }

    public void setCurrentCity(String currentCity) {
        this.currentCity = currentCity;
    }

    public List getWeather_data() {
        return weather_data;
    }

    public void setWeather_data(List weather_data) {
        this.weather_data = weather_data;
    }

    @Override
    public String toString() {
        return "Results{" +
                "currentCity='" + currentCity + '\'' +
                ", weather_data=" + weather_data +
                '}';
    }
}
public class WeatherResult {
    private String error;
    private String status;
    private String date;
    private List<Results> results;

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public List<Results> getResults() {
        return results;
    }

    public void setResults(List results) {
        this.results = results;
    }

    @Override
    public String toString() {
        return "WeatherResult [error=" + error + ", status=" + status
                + ", date=" + date + "]";
    }

}
public class Weather {
    private String date;
    private String dayPictureUrl;
    private String nightPictureUrl;
    private String weather;
    private String wind;
    private String temperature;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getDayPictureUrl() {
        return dayPictureUrl;
    }

    public void setDayPictureUrl(String dayPictureUrl) {
        this.dayPictureUrl = dayPictureUrl;
    }

    public String getNightPictureUrl() {
        return nightPictureUrl;
    }

    public void setNightPictureUrl(String nightPictureUrl) {
        this.nightPictureUrl = nightPictureUrl;
    }

    public String getWeather() {
        return weather;
    }

    public void setWeather(String weather) {
        this.weather = weather;
    }

    public String getWind() {
        return wind;
    }

    public void setWind(String wind) {
        this.wind = wind;
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    @Override
    public String toString() {
        return "Weather [date=" + date + ", dayPictureUrl=" + dayPictureUrl
                + ", nightPictureUrl=" + nightPictureUrl + ", weather="
                + weather + ", wind=" + wind + ", temperature=" + temperature
                + "]";
    }
}

小结:参考分档

https://blog.csdn.net/chengxc2016/article/details/52510936








                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值