遇到的问题一般Java不方便解析JSON:

1、出现JSON里面出现大量嵌套现象,如下JSON其中msg_item中嵌套了multi_item和send_stat的方式

2、出现几个对象列表的形式

然而此时却只需要部分数据,因此感觉不需要将每个字段都加到一个类里面来定义成一个对象。因此可以使用

JSONObject jo = JSONObject.fromObject(jsonString);

JSONArray jsons = jo.getJSONArray("msg_item");

方式来进行解析。

例如:如下JSON,即jsonString为如下信息


{
    "msg_item": [
            "id": 200520118,
            "type": 1,
            "fakeid": "953372741",
            "nick_name": "WWCCA",
            "date_time": 1405576147,
            "content": "CCCA",
            "source": "",
            "msg_status": 4,
            "has_reply": 0,
            "refuse_reason": "",
            "multi_item": [],
            "to_uin": 3092715931,
            "send_stat": {
                "total": 0,
                "succ": 0,
                "fail": 0
            "id": 200520110,
            "type": 1,
            "fakeid": "1437169916",
            "nick_name": "QS",
            "date_time": 1405575637,
            "content": "DDDW",
            "source": "",
            "msg_status": 4,
            "has_reply": 0,
            "refuse_reason": "",
            "multi_item": [],
            "to_uin": 3092715931,
            "send_stat": {
                "total": 0,
                "succ": 0,
                "fail": 0
}

具体解决方案如下所示


JSONObject jo = JSONObject.fromObject(personlistjson);
JSONArray jsons = jo.getJSONArray("msg_item");
int jsonLength = jsons.size();
Person ptemp = new Person();
for (int i = 0; i < jsonLength; i++) {
   JSONObject tempJson = JSONObject.fromObject(jsons.get(i));
   ptemp.setNickName(tempJson.get("nick_name").toString());
   ptemp.setFakeId(tempJson.get("fakeid").toString());
   ptemp.setContent(tempJson.get("content").toString());
   ptemp.setDateTime(tempJson.get("date_time").toString());
   persons.add(ptemp);
}

List<Person> persons即可获得所有需要的信息。


#!/usr/bin/env python #coding: utf-8 by guozheng_li #该脚本加入了文本、图片以及附件功能,日常运维跑的脚本基本也就这三样够用了。可以发送给多人,只要添加相应的mailto_list即可,再加入该说明前验证是正常的 import smtplib from email.mime.multipart import MIMEMultipart