java JSONObject 解析数组集合

2024-04-19 13:18

本文主要是介绍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_statif(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;}
}

 

 

 

 

 

这篇关于java JSONObject 解析数组集合的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/917646

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

一文解析C#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用