精华内容
下载资源
问答
  • java 生成json 格式的数据和json数据的遍历方法

        java 生成json 格式的数据,在需要加入一个创建json的jar包,这个网上有好多,我使用的是org.json的jar包。

    package com.dufy.javatojson;
    
    import java.util.Iterator;
    
    import javax.sound.midi.Synthesizer;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class TraverseJson {
    	
    	/**
    	 * 遍历json格式数据
    	 * @param json
    	 * @return
    	 */
    	public static Object traveseJson(Object json){
    		
    		if(json == null){
    			return null;
    		}
    		if(json instanceof JSONObject){//json 是一个map
    			//创建一个json对象
    			JSONObject jsonObj = new  JSONObject();
    			//将json转换为JsonObject对象
    			JSONObject jsonStr = (JSONObject) json;
    			//迭代器迭代 map集合所有的keys
    			Iterator it = jsonStr.keys();
    			while(it.hasNext()){
    				//获取map的key
    				String key = (String) it.next();
    				//得到value的值
    				Object value = jsonStr.get(key);
    				//System.out.println(value);
    				//递归遍历
    				jsonObj.put(key, traveseJson(value));
    				
    			}
    			return jsonObj;
    			
    		}else if(json instanceof JSONArray){// if  json 是 数组
    			JSONArray jsonAry = new JSONArray();
    			JSONArray jsonStr = (JSONArray) json;
    			//获取Array 的长度
    			int length = jsonStr.length();
    			for (int i = 0; i <length; i++) {
    				jsonAry.put(traveseJson(jsonStr.get(i)));
    			}
    			
    			return jsonAry;
    			
    		}else {//其他类型
    			
    			return json;
    		}
    		
    		
    		
    	}
    	
    	
    	
    	public static void main(String[] args) {
    		System.out.println(traveseJson("传入要遍历的json"));
    // 生成的JSON数据1  
    //		{
    //			"QQ":["742981086@qq.com","742981086"],
    //			"age":22,
    //		    "name":"aflyun",
    //			"hobby":["编程","看书","徒步","爬山","游泳"],
    //			"adderss":{"省份":"广东","市":"惠州","国籍":"中国"}
    //		}    
    		//创建 一个JsonObjec对象
    		 JSONObject resJsonObj = new JSONObject();
         	 //姓名
    		 resJsonObj.put("name", "aflyun");
    		 //年龄
    		 resJsonObj.put("age", 22);
    		 //联系方式
    		 JSONArray arryQq = new JSONArray();
    		 arryQq.put("742981086@qq.com").put("742981086");
    		 resJsonObj.put("QQ", arryQq);
    		 //地址 map
    		 JSONObject jsonAdress = new JSONObject();
    		 jsonAdress.put("国籍", "中国").put("省份", "广东").put("市", "惠州");
    		 resJsonObj.put("adderss", jsonAdress);
    		 //生成数组array
    		 JSONArray jArray = new JSONArray();
    		 jArray.put("编程").put("看书").put("徒步").put("爬山").put("游泳");
    		 resJsonObj.put("hobby", jArray);
    		 
    		 System.out.println(resJsonObj);
    		 
    		 System.err.println(traveseJson(resJsonObj));
    		 
    //数组类型的json格式数据生成		 
     //[
     //	{"hello":"你好"},
     //		[
     //			{"在干嘛":"编程"},
     //			["睡觉了吗","没有","不想睡","醒来了"]
     //		]
     //]
    		 
    		 JSONArray retJson = new JSONArray();
    		 //hello 
    		 JSONObject aJosn = new JSONObject();
    		 aJosn.put("hello", "你好");
    		 retJson.put(aJosn);
    		 //数组在干嘛和睡觉了吗 组装[]
    		 JSONArray jsa = new JSONArray();
    		 JSONObject jOne = new JSONObject();
    		 jOne.put("在干嘛", "编程");
    		 JSONArray jTwo = new JSONArray();
    		 jTwo.put("没有").put("不想睡").put("");
    		 JSONObject jOne1 = new JSONObject("醒来了");
    		 jOne1.put("睡觉了吗", jTwo);
    		 jsa.put(jOne).put(jOne1);
    		//将组装好的数据放入要返回的json数组中
    		 retJson.put(jsa);
    		 
    		 System.out.println("------" + retJson);
    		 System.err.println("------" + traveseJson(retJson));
    		 
    		 
    
    	}
    
    }

    通过运行上面的代码就能生成我们想要的json格式的数据,如下所示:

    {"QQ":["742981086@qq.com","742981086"],"age":22,"name":"aflyun","hobby":["编程","看书","徒步","爬山","游泳"],"adderss":{"省份":"广东","市":"惠州","国籍":"中国"}}
    ------[{"a":"a"},[{"b":"b"},{"c":[1,2,3]}]]
    {"QQ":["742981086@qq.com","742981086"],"name":"aflyun","age":22,"hobby":["编程","看书","徒步","爬山","游泳"],"adderss":{"省份":"广东","市":"惠州","国籍":"中国"}}
    ------[{"a":"a"},[{"b":"b"},{"c":[1,2,3]}]]

    举一反三 就可以生成我们想要的其他的json数据格式。。

    展开全文
  • JAVA爬取json数据

    2020-07-19 14:50:39
    JAVA爬取json数据 爬取码市上的项目生成文档方便查看。 查看码市的项目网址,便可看出这些项目都不是直接加载出来的,通过xhr看出是通过json的形式再次获取到的,获取到的地址中也可以看出分页也是通过最后的数字...

    JAVA爬取json数据

    爬取码市上的项目生成文档方便查看。

    查看码市的项目网址,便可看出这些项目都不是直接加载出来的,通过xhr看出是通过json的形式再次获取到的,获取到的地址中也可以看出分页也是通过最后的数字参数来进行区分的。

    码市项目页源码

    代码如下

    package Test.Write;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.eclipse.jetty.util.StringUtil;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    
    /**
     * 码市job
     * 
     * @author Zzh
     *
     */
    public class CatchJobs {
    
    	/**
    	 * 主程序
    	 * 
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// json集
    		List<String> jsons = new ArrayList<String>();
    		String htmlmain = "https://codemart.com/api/project?page=";
    		for (int i = 1; i <= 10; i++) {
    			String json = getJson(htmlmain + i);
    			jsons.add(json);
    		}
    		List<Job> jobList = parseJson(jsons);
    		exportExcel(jobList);
    	}
    
    	/**
    	 * 获取网页html代码
    	 * 
    	 * @param 网址
    	 */
    	private static String getJson(String path) {
    
    		// 保存整个html文档的数据
    		StringBuffer html = new StringBuffer();
    
    		try {
    			// 发起一个url网址的请求
    			URL url = new URL(path);
    			URLConnection connection = url.openConnection();
    
    			// 设置请求头
    			connection.addRequestProperty("Accept", "application/json");
    
    			// 获取网页的数据流
    			InputStream input = connection.getInputStream();
    			InputStreamReader reader = new InputStreamReader(input, "UTF-8");
    			BufferedReader bufferedReader = new BufferedReader(reader);
    
    			// 解析并且获取InputStream中具体的数据,并且输出到控制台
    			String line = "";
    			while ((line = bufferedReader.readLine()) != null) {
    				html.append(line);
    			}
    
    		} catch (MalformedURLException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return html.toString();
    	}
    
    	/**
    	 * 获取job
    	 * 
    	 * @param jobJsons
    	 * @return jobs
    	 */
    	private static List<Job> parseJson(List<String> jobJsons) {
    
    		// job集
    		List<Job> jobList = new ArrayList<Job>();
    
    		// 按每页的json数据循环
    		for (String jobJson : jobJsons) {
    			JSONObject json = JSONObject.fromObject(jobJson);
    
    			// 获取每页下的具体job数据
    			JSONArray rewardsJson = (JSONArray) json.get("rewards");
    			for (int i = 0; i < rewardsJson.size(); i++) {
    				Job job = new Job();
    				// 具体job信息
    				JSONObject reward = (JSONObject) rewardsJson.get(i);
    				job.setId(StringUtil.isNotBlank(reward.getString("id")) ? reward.getString("id") : "");
    				job.setName(StringUtil.isNotBlank(reward.getString("name")) ? reward.getString("name") : "");
    				job.setPrice(StringUtil.isNotBlank(reward.getString("price")) ? reward.getString("price") : "");
    				job.setStatusText(
    						StringUtil.isNotBlank(reward.getString("statusText")) ? reward.getString("statusText") : "");
    				job.setDescription(
    						StringUtil.isNotBlank(reward.getString("description")) ? reward.getString("description") : "");
    				job.setDuration(
    						StringUtil.isNotBlank(reward.getString("duration")) ? reward.getString("duration") : "");
    				job.setRoles(StringUtil.isNotBlank(reward.getString("roles")) ? reward.getString("roles") : "");
    				jobList.add(job);
    			}
    		}
    
    		return jobList;
    	}
    
    	/**
    	 * 导出excel
    	 * 
    	 * @param job内容
    	 */
    	private static void exportExcel(List<Job> jobs) {
    
    		// 定义表头
    		String[] title = { "项目编号", "名字", "价格", "状态", "介绍", "周期", "分类" };
    		// 创建excel工作簿
    		HSSFWorkbook workbook = new HSSFWorkbook();
    		// 创建工作表sheet
    		HSSFSheet sheet = workbook.createSheet();
    		// 创建第一行
    		HSSFRow row = sheet.createRow(0);
    		HSSFCell cell = null;
    		// 插入第一行数据的表头
    		for (int i = 0; i < title.length; i++) {
    			cell = row.createCell(i);
    			cell.setCellValue(title[i]);
    		}
    
    		// 写入数据
    		int i = 1;
    		for (Job job : jobs) {
    			HSSFRow nrow = sheet.createRow(i);
    			HSSFCell ncell = nrow.createCell(0);
    			ncell.setCellValue(job.getId());
    			ncell = nrow.createCell(1);
    			ncell.setCellValue(job.getName());
    			ncell = nrow.createCell(2);
    			ncell.setCellValue(job.getPrice());
    			ncell = nrow.createCell(3);
    			ncell.setCellValue(job.getStatusText());
    			ncell = nrow.createCell(4);
    			ncell.setCellValue(job.getDescription());
    			ncell = nrow.createCell(5);
    			ncell.setCellValue(job.getDuration());
    			ncell = nrow.createCell(6);
    			ncell.setCellValue(job.getRoles());
    			i++;
    		}
    
    		// 创建excel文件
    		File file = new File("d://码市.xlsx");
    		try {
    			file.createNewFile();
    			// 将excel写入
    			FileOutputStream stream = FileUtils.openOutputStream(file);
    			workbook.write(stream);
    			stream.close();
    			System.out.println("出力好了");
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }

    这样就可以通过生成的文件直接查看啦

     

    展开全文
  • java 处理 json数据

    千次阅读 2018-10-19 14:34:15
    Json数据样例: {“1”:[1,4,3,2],“2”:[1],“3”:[1,4,3,2],“4”:[1,6,5,4,3,2],“5”:[7,1,6,5,4,3,2,8,9],“6”:[7,1,8,2,3,9,4,5,6],“7”:[7,1,8,2,3,9,6,5,4],“9”:[1,2,3,4,5,6],“15”:[1,4,3,2]} java...

    Json数据样例一,解析简单json:

    {"1":[1,4,3,2],"2":[1],"3":[1,4,3,2],"4":[1,6,5,4,3,2],"5":[7,1,6,5,4,3,2,8,9],"6":[7,1,8,2,3,9,4,5,6],"7":[7,1,8,2,3,9,6,5,4],"9":[1,2,3,4,5,6],"15":[1,4,3,2]}
    

    java代码:

    List<String> key = new ArrayList<String>();
    //将字符串转json对象
    JSONObject json1=JSONObject.parseObject(json);  
    //将json对象转map
    Map<String, Object> map2 =json1;  
    //遍历map
    for (Entry<String, Object> entry : map2.entrySet()) {  
    	String str = String.valueOf(entry.getValue());
    	String temp = str.substring(1,str.length()-1);
    	String[] array = temp.split(",");
    	List<String> list = new ArrayList<String>();
    	for (int i = 0; i < array.length; i++) {
    		list.add(array[i]);
    	}
    	if(list.contains("1"))
    	{
    		key.add(entry.getKey());
    	}
    } 
    

    使用实例二:
    json数据样例:

    String json = "{"
    		+"\"error_code\": 0,"
    		+"\"resultcode\": \"200\","
    		+"\"reason\": \"成功的返回\","
    		+"\"result\": {"
    			+"\"BJ\": {"
    				+"\"province\": \"北京\","
    				+"\"citys\": [{"
    					+"\"city_name\": \"北京\","
    					+"\"city_code\": \"BJ\","
    					+"\"abbr\": \"京\","
    					+"\"engine\": \"1\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"0\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"}]"
    					+"},"
    			+"\"SH\": {"
    				+"\"province\": \"上海\","
    				+"\"citys\": [{"
    					+"\"city_name\": \"上海\","
    					+"\"city_code\": \"SH\","
    					+"\"abbr\": \"沪\","
    					+"\"engine\": \"1\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"0\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"}]"
    					+"},"
    		+"\"LN\": {"
    			+"\"province\": \"辽宁\","
    			+"\"citys\": [{"
    					+"\"city_name\": \"沈阳\","
    					+"\"city_code\": \"LN_SY\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"4\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"锦州\","
    					+"\"city_code\": \"LN_JZ\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"6\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"营口\","
    					+"\"city_code\": \"LN_YK\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"葫芦岛\","
    					+"\"city_code\": \"LN_HLD\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"大连\","
    					+"\"city_code\": \"LN_DL\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"鞍山\","
    					+"\"city_code\": \"LN_AS\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"4\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"抚顺\","
    					+"\"city_code\": \"LN_FS\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"4\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"丹东\","
    					+"\"city_code\": \"LN_DD\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"1\","
    					+"\"engineno\": \"3\","
    					+"\"class\": \"0\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"阜新\","
    					+"\"city_code\": \"LN_FX\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"1\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"0\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"辽阳\","
    					+"\"city_code\": \"LN_LY\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"铁岭\","
    					+"\"city_code\": \"LN_TL\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"1\","
    					+"\"registno\": \"1\""
    					+"},"
    					+"{"
    					+"\"city_name\": \"朝阳\","
    					+"\"city_code\": \"LN_CY\","
    					+"\"abbr\": \"辽\","
    					+"\"engine\": \"0\","
    					+"\"engineno\": \"0\","
    					+"\"class\": \"1\","
    					+"\"classno\": \"0\","
    					+"\"regist\": \"0\","
    					+"\"registno\": \"0\""
    					+"}"
    					+"]"
    					+"}"
    					+"}"
    					+"}";
    

    解析json代码展示:

    	
    	JSONObject json1=JSONObject.parseObject(json);  
    	String str = json1.getString("result");
    	JSONObject str_=JSONObject.parseObject(str);
    	Map<String, Object> map2 =str_;
    //		System.out.println(map2.size());
    		for (Entry<String, Object> entry : map2.entrySet()) {
    			String key = entry.getKey();
    			String value = entry.getValue().toString();
    //			System.out.println("map2: "+key + " == " + value);
    			JSONObject map_json = JSONObject.parseObject(value);
    			Map<String, Object> map3 =map_json;
    			for (Entry<String, Object> entry3 : map3.entrySet()) {
    				String key_ = entry3.getKey();
    				String value_ = entry3.getValue().toString();
    				System.out.println("map_json: "+key_ + " == " + value_);
    				if(!value_.startsWith("[{") && !value_.endsWith("}]"))
    				{
    					break;
    				}
    				JSONArray map_map_json = JSONArray.parseArray(value_);
    				System.out.println(map_map_json.size());
    				for (int i = 0; i < map_map_json.size(); i++) {
    					System.out.println("  =========" + map_map_json.get(i));
    					Object obj =map_map_json.get(i);
    					JSONObject map_map_json_ = JSONObject.parseObject(obj.toString());
    					Map<String, Object> map4 =map_map_json_;
    					for (Entry<String, Object> entry4 : map4.entrySet()) {
    						String key_4 = entry4.getKey();
    						String value_4 = entry4.getValue().toString();
    						System.out.println("map_map_json_: "+key_4 + " == " + value_4);
    					}
    				}
    			}
    		}
    

    (2)解析json型的字符串:

    String datas="{\"imei\":\"358732036143010\",\"version\":\"2.3\",\"apk\":[{\"appname\":\"SyncKey\",\"packagename\":\"com.discovery.synckey\"},{\"appname\":\"DbTest\",\"packagename\":\"com.discovery.synckey\"},{\"appname\":\"AppUpdate\",\"packagename\":\"com.discovery.synckey\"}]}";
    
    JSONObject reqJson=JSONObject.parseObject(datas);
    String imei=reqJson.getString("imei");
    String apk=reqJson.getString("apk");//json型集合
    JSONArray parseArry =JSONObject.parseArray(apk);
    Iterator<Object> iterator =parseArry.iterator();
    while(iterator.hasNext())
    {
      JSONObject object =(JSONObject)iterator.next();
           String  appname =(String)object.getString("appname")
    }
    

    json解析多节点json数据时,主要是分析json格式,找到规律循环遍历;如果没有规律可循,可以层层解析,找到需要的数据节点。

    {
        "requestId": "SMELP_DATA_CUSTOMS_8062a1b4-a954-4fd1-8ded-40fdf7594296",
        "responseData": {
            "loadType": "2--2",
            "records": [
                {
                    "erMsg": "'银行卡号'卡BIN校验未通过",
                    "seqNo": "0",
                    "cardType": "",
                    "authResult": "",
                    "erCode": "E000001",
                    "bankName": ""
                }
            ],
            "detailError": null,
            "responseMessage": "接口调用成功!",
            "requestNo": "123",
            "transNo": null,
            "dataSource": null,
            "responseCode": "000000"
        },
        "responseMessage": "请求成功",
        "responseCode": "000000"
    }
    

    例如获取erMsg里的信息:

       //result是调用接口之后返回的String类型的json串
       JSONObject obj = JSONObject.parseObject(result);
       JSONObject responseData = (JSONObject) obj.get("responseData");
       JSONArray records = (JSONArray) responseData.get("records");
       JSONObject erMsg1 =  (JSONObject) records.get(0);            
       String erMsg = erMsg1.getString("erMsg");
    

    例如获取responseMessage里的信息:

    JSONObject obj = JSONObject.parseObject(result);
    String msg = obj.getString("responseMessage");
    
    展开全文
  • Java遍历Json数据

    万次阅读 2019-05-17 21:53:46
    今天需要遍历一下json,但是只查到了遍历一层json的文章,满足不了多层级的json遍历。所以自己写一下,用fastJson处理。 所遍历json需要考虑一下多层级的json,需要考虑的就是 JSONObject 和JSONArray 两种情况,对...

    今天需要遍历一下json,但是只查到了遍历一层json的文章,满足不了多层级的json遍历。所以自己写一下,用fastJson处理。

    所遍历json需要考虑一下多层级的json,需要考虑的就是 JSONObject 和 JSONArray 两种情况,对这两种情况做处理,采用递归向下遍历,用instanceof判断递归到的类型,做不同处理。下边贴上代码:

    public class JsonLoop {
    
        public static String json = "{\"TITLE\":\"Json Title\",\"FORM\":{\"USERNAME\":\"Rick and Morty\"},\"ARRAY\":[{\"FIRST\":\"Rick\"},{\"LAST\":\"Morty\"}]}";
    
        public static void jsonLoop(Object object) {
    
            if(object instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) object;
                for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                    Object o = entry.getValue();
                    if(o instanceof String) {
                        System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
                    } else {
                        jsonLoop(o);
                    }
                }
            }
            if(object instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) object;
                for(int i = 0; i < jsonArray.size(); i ++) {
                    jsonLoop(jsonArray.get(i));
                }
            }
        }
    
        public static void main(String[] args) {
    
            JSONObject jsonObject = JSON.parseObject(json);
            jsonLoop(jsonObject);
        }
    }

     遍历如下包含 JSONObject 和 JSONArray 的json数据:

    {
        "TITLE":"Json Title",
        "FORM":{
            "USERNAME":"Rick and Morty"
        },
        "ARRAY":[
            {
                "FIRST":"Rick"
            },
            {
                "LAST":"Morty"
            }
        ]
    }

     下边是输出结果:

    key:FIRST,value:Rick
    key:LAST,value:Morty
    key:USERNAME,value:Rick and Morty
    key:TITLE,value:Json Title

    展开全文
  • Java XML JSON 数据解析

    千次阅读 2013-06-26 14:07:22
    下面我们通过一段代码了解一下解析JSON格式数据的基本过程: 提示:使用JSON需要导入 JSON 相关的多个Jar文件 import net.sf.json.JSONObject; public class JsonUtil { public static void parseJson(String ...
  • javajson数据格式的应用 分类: json2012-08-29 11:29 333人阅读 评论(0) 收藏 举报 jsonjavastringlistclassobject 最近做的项目中有一个android的客户端,但是由于手机 如果用xml格式传输数据...
  • 关键在于好的算法这个代码来源于网络,算法已在注释中添加。 工具地址: 链接:https://pan.baidu.com/s/1Ns3cqi0SG3qSqatrZBrl4A 提取码:2... ... * 该类的方法formatJson将JSON字符串格式化,方便查看JSON数据...
  • 1. 把java 对象列表转换为json对象数组,并转为字符串 复制代码 代码如下:  JSONArray array = JSONArray.fromObject(userlist);  String jsonstr = array.toString(); 2.把java对象转换成json对象,并转化为...
  • 省市区联动在项目中算是比较常见的功能了,但是基础数据却非常多,网上很难找到比较全的数据,不过在github上有人利用爬虫抓取了国家统计局的数据,并生成了json文件,这样就可以利用java解析json文件并生成相应的...
  • java转换成json数据: String json = JSONObject.toJsonString(java 对象); 将java对象转换成json时,名称可以自己来指定: @JSOMField(name = “编号”) java对象中存在日期类型属性java.util.Date,可以用...
  • 为什么要使用js-xlsx呢? 假如我们遇到了这样一个需求,把数据库中的数据导出位Excel,或者把Excel导入到数据库(这里以导出Excel为例). ...通过json数据创建一个表 把表添加到工作簿 最后写出文件 //创...
  • 在用java传输json数据时,map类型的变量里的数据会被最后一次赋值的内容所覆盖:package MicrosoftImageCup;import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import ...
  • 如何使用Java循环解析json

    千次阅读 2019-04-30 19:15:46
    * @param code 传入json数据解析 * @return */ public static String analysisJson(String code) { List list = new ArrayList<>(); //fastjson解析方法 JSONObject json = JSONObject.parseObject...
  • 在www.json.org上公布了很多JAVA下的...下面首先介绍用json-lib构造和解析Json数据的方法示例。 一、介绍  JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包,主要就是用来解析Json
  • 在服务器与web前端、移动端进行数据交互的时候的时候,通常会调用接口url把数据以JSON数据格式传过去进行显示,因此,JSON数据格式在前后端数据交互时会经常用到。 目录 前言 什么是JSON? 标准的JSON数据表示: ...
  • java遍历json数组

    千次阅读 2018-10-17 14:03:20
    我们用java解析json数据是用: JSONObject jsonObject = JSONObject.parseObject(str);就能获取到json的数据了并根据key取value,但是注意json数据串里如果有数组的话这么取值肯定会有问题的,因为JSONObject 只能...
  • java后台处理json数据

    千次阅读 2018-04-19 09:49:10
    1.前台传到后台一个map,map里面是json格式的数据JSONObject jsonObject=JSONObject.fromObject(map);//把map转成json格式,输出一下看是什么数据格式可以把这个jsonObject打印到控制台 复制到 json在线解析及格式...
  • js和java按照json格式导出数据

    千次阅读 2016-03-03 21:16:52
    js和java按照json格式导出数据 工作中遇到了需要从表中取出大量数据后,再和所得数据进行对比取值的事,这不能一个数据一个数据的录吧,于是就取了点巧,自己写了一个简单的程序,真是节省了我的不少时间,废话少...
  • JAVA 循环读取JSON内容

    2012-04-18 10:21:16
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);  String json_c = jsonArray.getString(0 );  JSONObject jsonObject = JSONObject.fromObject(json_c);  for  ...
  • java 后台封装json数据

    万次阅读 2012-07-11 14:05:37
    1. List集合转换成json代码 List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); 2. Map集合转换成json代码 Map map = new ...
  • java后台封装json数据(一)

    千次阅读 2017-07-19 14:02:49
    数据封装 1. List集合转换成json代码  List list = new ArrayList();  list.add( "first" );  list.add( "second" );  JSONArray jsonArray2 = JSONArray.fromObject( list ); 2. Map集合转换成json代码...
  • Java使用org.json.jar构造和解析Json数据

    万次阅读 2017-09-06 22:47:06
    Java使用org.json.jar构造和解析Json数据
  • 最近工作解析json数据比较多,使用org.JSONObject和org.JSONArray ,net.sf.JSONObject 比较多,希望一下内容可以帮助大家节省时间填坑 想使用当然得下载jar包 org.JSONObject org.JSONArray下载地址...
  • JSON是我们在数据传输中最常用的格式,一般在RESTful的接口设计中返回的一般都是JSON。在Java中经常要来完成数据解析的任务。本文就来实现如何在Java中如何解析JSON。 这里我们使用的工具是Alibaba的FastJSON,根据...
  • java数据转化
  • 是一对多的数据结构,一个栏目对应多个文章 ``` Category: List<Article> articleList; Article: String categoryId; Category category; ``` 业务: ``` foreach(Category item:categoryList){ item....
  • 在www.json.org上公布了很多JAVA下的json构造和解析工具,其中org.json和json-lib... 用org.son构造和解析Json数据的方法详解请参见我下一篇博文:Java构造和解析Json数据的两种方法详解二 一、介绍  JSON-l

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 51,614
精华内容 20,645
关键字:

java循环json数据

java 订阅