java JSONObject 解析数组集合

数据源:

{
    "msg": "成功",
    "code": 0,
    "data": {
        "pagination": {
            "total_count": 2,
            "limit": 20,
            "page": 1
        },
        "videos": [
            {
                "video_stat": {
                    "total_share": 9,
                    "total_play": 43397,
                    "total_like": 1131,
                    "total_comment": 37
                },
                "author": {
                    "tags_author_style": "[]",
                    "next_month_show_price": 0,
                    "long_video_price": 12000,
                    "follower": 1413712,
                    "create_time": 1543604473,
                    "tags_ids": "[36, 1]",
                    "avg_play": 203863,
                    "abandon_sign_result": 0,
                    "id": "6629730730584834056",
                    "appeal_id": 0,
                    "city": "广州市",
                    "next_month_long_video_show_price": 0,
                    "short_id": 1698079787,
                    "show_price": 8400,
                    "cut_rate": 0.0,
                    "online_status": 1,
                    "tags_level_two": "[\"\好\物\推\荐\", \"\护\肤\保\养\", \"\生\活\小\窍\门\"]",
                    "lowest_price": 2000,
                    "price": 8000,
                    "author_type": 2,
                    "province": "广东省",
                    "tags": "[\"\美\妆\", \"\生\活\"]",
                    "next_month_long_video_price": 12000,
                    "next_month_price": 8000,
                    "is_online": true,
                    "has_phone": true,
                    "core_user_id": 106056671938,
                    "task_status": 2,
                    "protocol_id": 2018006,
                    "nick_name": "汪四姨",
                    "gender": 2,
                    "opened_task_category": "[1]",
                    "rate": 1.05,
                    "tags_ids_level_two": "[40, 39, 4]",
                    "modify_time": 1571292137,
                    "avatar_uri": "https://p3-dy.byteimg.com/aweme/1080x1080/2dd8b0003895b59fbc230.jpeg",
                    "long_video_show_price": 12600,
                    "category_id": 5,
                    "unique_id": 1698079787
                },
                "order": {
                    "status": 3,
                    "facilitator_id": 0,
                    "ad_intent": 2,
                    "auditing_item_id": "0",
                    "money": 12600,
                    "platform_source": 1,
                    "producer_id": "6629730730584834056",
                    "video_type": 2,
                    "item_status": 999,
                    "bill_status": 3,
                    "approved_item_upload_invoke_src": "1",
                    "component_id": "0",
                    "release_time": 1567331369.0,
                    "item_id": "6731565643545562380",
                    "audit_status": 4,
                    "cover_image_uri": "tos-cn-p-0015/cdf4354abba44ac5b62cb0c6bedfa8c2",
                    "id": "6727929591672864772",
                    "desc": "21-60s视频",
                    "need_release_video": true,
                    "accept_timestamp": 1566468443.0,
                    "demander_evaluate_status": 0,
                    "component_type": 0,
                    "video_title": "美白淡斑?去痘印?有它就够了!#美白 #长痘长痘 #男神 #抖出你的范儿",
                    "finish_time": 1567392883.0,
                    "demand_id": "6727929591614144524",
                    "author_cancel_status": 0,
                    "pay_mode": 1,
                    "ignore_script": false,
                    "last_operator_role": 1,
                    "create_time": 1566468177.0,
                    "evaluate_status": 0,
                    "accept_time": "2019-08-22 18:07:23",
                    "author_evaluate_status": 0,
                    "accept_available_time": 1566468177,
                    "confirm_cancel": 0,
                    "ecom_draft_id": "0",
                    "modify_time": 1568106712.0
                },
                "demand": {
                    "facilitator_id": null,
                    "second_class_category": 190202,
                    "product_information": "品牌: ROHTO 面部精华单品: ROHTOMELANO-CC精华液  功效: 提亮肤色 保湿 控油 祛痘\n产品链接:https://detail.tmall.hk/hk/item.htm?spm=a212k0.12153887.0.0.3099687dNDoC8B&id=592404071863&skuId=4073160872556",
                    "component_category": null,
                    "contact_id": "6727992979060949006",
                    "demand_type": 2,
                    "create_time": 1566468177,
                    "id": "6727929591614144524",
                    "category": 0,
                    "total_pay": 25200,
                    "title": null,
                    "release_user_id": "6700703634801295372",
                    "component_info": null,
                    "other": "{\"music\":\"\",\"makeupType\":\"\",\"propDemand\":\"\",\"sceneDemand\":\"\",\"detailDemand\":\"具体以给到的brief为准出脚本\"}",
                    "expiration_time_end": 1567180800,
                    "attachment": null,
                    "expiration_time": 1566748800,
                    "product_name": "品牌: ROHTO 乐敦 CC美容精华液",
                    "video_ratio": null,
                    "status": 1,
                    "activity_id": "0",
                    "first_class_category_name": "快速消费品",
                    "ignore_script": false,
                    "wechat": null,
                    "ad_intent": 2,
                    "task_category": 1,
                    "qq": null,
                    "landing_page": null,
                    "component_id": 0,
                    "name": "品牌: ROHTO 乐敦 CC美容精华液_0822_17:59",
                    "component_type": 0,
                    "second_class_category_name": "一般化妆品",
                    "contact": "青锋",
                    "brand_introduction": null,
                    "modify_time": 1566482935,
                    "first_class_category": 1902,
                    "need_structure": true,
                    "template_id": 0,
                    "activity_type": 1
                }
            },
            {
                "video_stat": {
                    "total_share": 31,
                    "total_play": 106032,
                    "total_like": 2354,
                    "total_comment": 139
                },
                "author": {
                    "tags_author_style": "[\"\知\识\"]",
                    "next_month_show_price": 0,
                    "long_video_price": 10800,
                    "follower": 2111452,
                    "create_time": 1553513294,
                    "tags_ids": "[36, 1]",
                    "avg_play": 584996,
                    "abandon_sign_result": 0,
                    "id": "6672288792474288136",
                    "appeal_id": 0,
                    "city": "广州市",
                    "next_month_long_video_show_price": 0,
                    "short_id": 1815369178,
                    "show_price": 6300,
                    "cut_rate": 0.0,
                    "online_status": 1,
                    "tags_level_two": "[\"\护\肤\保\养\", \"\美\妆\测\评\种\草\", \"\生\活\小\窍\门\"]",
                    "lowest_price": 2000,
                    "price": 6000,
                    "author_type": 1,
                    "province": "广东省",
                    "tags": "[\"\美\妆\", \"\生\活\"]",
                    "next_month_long_video_price": 10800,
                    "next_month_price": 6000,
                    "is_online": true,
                    "has_phone": true,
                    "core_user_id": 108614783430,
                    "task_status": 1,
                    "protocol_id": 2018006,
                    "nick_name": "总剁主小猪",
                    "gender": 1,
                    "opened_task_category": "[1]",
                    "rate": 1.05,
                    "tags_ids_level_two": "[39, 4, 5]",
                    "modify_time": 1571292119,
                    "avatar_uri": "https://p3-dy.byteimg.com/aweme/1080x1080/2dd83000123fad16a1771.jpeg",
                    "long_video_show_price": 11340,
                    "category_id": 1,
                    "unique_id": "wuyue0937"
                },
                "order": {
                    "status": 3,
                    "facilitator_id": 0,
                    "ad_intent": 2,
                    "auditing_item_id": "0",
                    "money": 12600,
                    "platform_source": 1,
                    "producer_id": "6672288792474288136",
                    "video_type": 2,
                    "item_status": 999,
                    "bill_status": 4,
                    "approved_item_upload_invoke_src": "1",
                    "component_id": "0",
                    "release_time": 1567224960.0,
                    "item_id": "6730933731474951437",
                    "audit_status": 4,
                    "cover_image_uri": "tos-cn-p-0015/bb324d2bd35945ff9532278c7910a371",
                    "id": "6727929591723196429",
                    "desc": "21-60s视频",
                    "need_release_video": true,
                    "accept_timestamp": 1566468244.0,
                    "demander_evaluate_status": 0,
                    "component_type": 0,
                    "video_title": "这个不到100块的精华竟然颠覆了我的三观......#美白 #淡斑 #平价护肤 #痘印痘坑",
                    "finish_time": 1567392870.0,
                    "demand_id": "6727929591614144524",
                    "author_cancel_status": 0,
                    "pay_mode": 1,
                    "ignore_script": false,
                    "last_operator_role": 1,
                    "create_time": 1566468177.0,
                    "evaluate_status": 0,
                    "accept_time": "2019-08-22 18:04:04",
                    "author_evaluate_status": 0,
                    "accept_available_time": 1566468177,
                    "confirm_cancel": 0,
                    "ecom_draft_id": "0",
                    "modify_time": 1568106712.0
                },
                "demand": {
                    "facilitator_id": null,
                    "second_class_category": 190202,
                    "product_information": "品牌: ROHTO 面部精华单品: ROHTOMELANO-CC精华液  功效: 提亮肤色 保湿 控油 祛痘\n产品链接:https://detail.tmall.hk/hk/item.htm?spm=a212k0.12153887.0.0.3099687dNDoC8B&id=592404071863&skuId=4073160872556",
                    "component_category": null,
                    "contact_id": "6727992979060949006",
                    "demand_type": 2,
                    "create_time": 1566468177,
                    "id": "6727929591614144524",
                    "category": 0,
                    "total_pay": 25200,
                    "title": null,
                    "release_user_id": "6700703634801295372",
                    "component_info": null,
                    "other": "{\"music\":\"\",\"makeupType\":\"\",\"propDemand\":\"\",\"sceneDemand\":\"\",\"detailDemand\":\"具体以给到的brief为准出脚本\"}",
                    "expiration_time_end": 1567180800,
                    "attachment": null,
                    "expiration_time": 1566748800,
                    "product_name": "品牌: ROHTO 乐敦 CC美容精华液",
                    "video_ratio": null,
                    "status": 1,
                    "activity_id": "0",
                    "first_class_category_name": "快速消费品",
                    "ignore_script": false,
                    "wechat": null,
                    "ad_intent": 2,
                    "task_category": 1,
                    "qq": null,
                    "landing_page": null,
                    "component_id": 0,
                    "name": "品牌: ROHTO 乐敦 CC美容精华液_0822_17:59",
                    "component_type": 0,
                    "second_class_category_name": "一般化妆品",
                    "contact": "青锋",
                    "brand_introduction": null,
                    "modify_time": 1566482935,
                    "first_class_category": 1902,
                    "need_structure": true,
                    "template_id": 0,
                    "activity_type": 1
                }
            }
        ],
        "total_video_stat": {
            "total_share": 40,
            "total_play": 149429,
            "total_like": 3485,
            "total_comment": 176
        }
    }
}

 

http获取json数据

package com.ruoyi.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
import java.util.*;

import java.io.BufferedWriter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.base.SystemData;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
 * 但不够简便;
 *
 * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
 * 4.以输入流的形式获取返回内容 5.关闭输入流
 *
 * @author
 *
 */
public class HttpConnectionUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    

    /**
     * post提交
     * @param url 接收的url
     * @param parameter 接收的参数
     * @return 返回结果
     */
    public static String sendPost(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("POST");
            byte contentbyte[] = parameter.toString().getBytes();
            //设置请求类型
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置表单长度
            conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
            //设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
            //连接主机的超时时间(单位:毫秒)
            conn.setConnectTimeout(60000);
            //从主机读取数据的超时时间(单位:毫秒)
            conn.setReadTimeout(60000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在    2
            // http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            bWriter.write(parameter.toString());


            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i != -1;) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();
            //此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

            result = new String(buffer.toString().getBytes("iso-8859-1"), "UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param,Map<String,String> requestPropertyMap)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = url;
            if(param != null && !"".equals(param)){
                if(urlNameString.contains("?")){
                    urlNameString = urlNameString + "&" + param;
                }else{
                    urlNameString = urlNameString + "?" + param;
                }
            }
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //批量requestPropertyList赋值
            if(requestPropertyMap != null && requestPropertyMap.size() > 0){
                for (Map.Entry<String, String> entry : requestPropertyMap.entrySet()) {
//                    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//                    connection.setRequestProperty("Cookie", "");
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }


}

 

解析:


    /**
     * 任务需求(详情)及相关订单(视频)、作者 列表 数据解析
     * @param  url 访问地址
     * @param  cookie header中的cookie值
     *
     * @return
     */
    public static Map<String,Object> order_video_list(String url,String cookie) {
        Map<String,String> map = new HashMap<>();
        map.put("Cookie", cookie);
        String resp = HttpConnectionUtil.sendGet(url,null,map);
        Map<String,Object> resMap = new HashMap<>();
        try {
            StringBuffer sb=new StringBuffer();
            sb.append("");
            JSONObject respJson=JSONObject.parseObject(resp);
            resMap.put("code",respJson.getString("code"));
            resMap.put("msg",respJson.getString("msg"));
            if("0".equals(respJson.getString("code")) && respJson.getString("data") != null){
                respJson = JSONObject.parseObject(respJson.getString("data"));
                //分页
                if(respJson.getString("pagination") != null){
                    PaginationJsonObj pagination = JSONObject.parseObject(respJson.getString("pagination"),PaginationJsonObj.class);
                    resMap.put("pagination",pagination);
                }
                //订单任务互动数据 观看、点赞、收藏、分享
                if(respJson.getString("total_video_stat") != null){
                    VideoStatJsonObj totalVideoStat = JSONObject.parseObject(respJson.getString("total_video_stat"), VideoStatJsonObj.class);
                    resMap.put("totalVideoStat",totalVideoStat);
                }
                //订单(视频)、需求、作者、互动数据
                if(respJson.getString("videos") != null){
                    JSONArray videos = JSON.parseArray(respJson.getString("videos"));
//                    demand  order   author   video_stat
                    if(videos != null && videos.size() > 0){
                        for (int i = 0; i < videos.size(); i++) {
                            JSONObject videoJson = (JSONObject) videos.get(i);

                            if(videoJson.getString("video_stat") != null){
                                VideoStatJsonObj videoStat = JSONObject.parseObject(videoJson.getString("video_stat"),VideoStatJsonObj.class);
                                System.out.println(videoStat.getTotal_play());
                            }

                            if(videoJson.getString("author") != null){
                                DemandVideoAuthorJsonObj author = JSONObject.parseObject(videoJson.getString("author"),DemandVideoAuthorJsonObj.class);
                                System.out.println(author.getNick_name());
                            }

                            if(videoJson.getString("order") != null){
                                DemandOrderJsonObj order = JSONObject.parseObject(videoJson.getString("order"),DemandOrderJsonObj.class);
                                System.out.println(order.getVideo_title());
                            }

                            if(videoJson.getString("demand") != null){
                                DemandDetailJsonObj demand = JSONObject.parseObject(videoJson.getString("demand"),DemandDetailJsonObj.class);
                                System.out.println(demand.getName());
                            }

                        }

                    }
                }

            }else{
                log.error("解析接口数据失败,错误提示: " + respJson.getString("msg") + " " + url);
            }
        } catch (Exception e) {
            return null;
        }
        return resMap;
    }

相关对象:

package com.ruoyi.system.domain.jsonObj;

/**
 * 解析互动数据 json对象
 * 
 */
public class VideoStatJsonObj
{

	public Long total_play;

	public Integer total_like;

	public Integer total_comment;

	public Integer total_share;

	public Long getTotal_play() {
		return total_play;
	}

	public void setTotal_play(Long total_play) {
		this.total_play = total_play;
	}

	public Integer getTotal_like() {
		return total_like;
	}

	public void setTotal_like(Integer total_like) {
		this.total_like = total_like;
	}

	public Integer getTotal_comment() {
		return total_comment;
	}

	public void setTotal_comment(Integer total_comment) {
		this.total_comment = total_comment;
	}

	public Integer getTotal_share() {
		return total_share;
	}

	public void setTotal_share(Integer total_share) {
		this.total_share = total_share;
	}
}

 

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用`JSON.parseObject`解析复杂类型时,需要注意以下几点: 1. 确定要解析的JSON字符串格式是否符合要求,例如是否符合对应的Java对象结构。 2. 创建对应的Java对象,确保它的属性结构与JSON字符串一致。 3. 使用`JSON.parseObject`方法进行解析,将JSON字符串转换为Java对象。 下面是一个示例,演示如何使用`JSON.parseObject`解析复杂类型的JSON字符串: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class Main { public static void main(String[] args) { String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"}}"; // 解析JSON字符串为Java对象 JSONObject jsonObject = JSON.parseObject(jsonString); // 获取属性值 String name = jsonObject.getString("name"); int age = jsonObject.getIntValue("age"); // 解析嵌套的复杂类型属性 JSONObject addressObject = jsonObject.getJSONObject("address"); String street = addressObject.getString("street"); String city = addressObject.getString("city"); // 打印解析结果 System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Street: " + street); System.out.println("City: " + city); } } ``` 在上面的示例中,我们首先定义了一个包含嵌套对象的JSON字符串。然后使用`JSON.parseObject`方法将其解析为`JSONObject`对象。接下来,我们使用`getString`和`getIntValue`方法获取简单类型的属性值,使用`getJSONObject`方法获取嵌套对象的属性值。最后,我们打印解析结果。 注意:在使用`JSON.parseObject`解析复杂类型时,需要确保JSON字符串的格式正确,且Java对象的属性结构与JSON字符串一致。另外,引入Fastjson库可以方便地进行JSON解析操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值