赞
踩
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
package com.hao.sftp; import com.alibaba.fastjson.JSON; import org.junit.Test; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** * @Author: Java页大数据 * @Date: 2022-05-09:19:22 * @Describe: * 1.使用ConcurrentHashMap,为线程安全的map类型;此处不用hashmap,因为hashmap为非线程安全! * 2.初学之前,遇到json格式,我都习惯用一个类的属性来封装数据,但是后来了解到对象的属性,其实就是一个map类型! * 3.如果有多层的话,就用到了List! * 4.此处用if语句来判断一些属性时为缺失的!或者说根据i的奇偶来获取不同的值 * 5.多习惯这种写法,因为看框架的时候就没怎么看到会有用类来封装数据 */ public class TestMap { @Test public void test01(){ ArrayList<Object> lists = new ArrayList<>(); for (int i = 1; i <= 10; i++) { ConcurrentHashMap<String , Object> concurrentHashMap = new ConcurrentHashMap<>(20); concurrentHashMap.put("id", i ); concurrentHashMap.put("age", i + new Random().nextInt(85)); concurrentHashMap.put("name", "javaAndBigdata" + new Random().nextInt(85)); if (i % 3 == 0){ concurrentHashMap.put("grade", "low"); // concurrentHashMap.put("hobby", i % 2 == 0 ? "tv" : "sleeping"); // 控制该属性可有可无!!! }else if (i % 3 == 1){ concurrentHashMap.put("grade", "midden"); concurrentHashMap.put("hobby", i % 2 == 0 ? "football" : "tennis"); }else { concurrentHashMap.put("grade", "high"); concurrentHashMap.put("hobby", i % 2 == 0 ? "basketball" : "table tennis"); } lists.add(concurrentHashMap); } String s = JSON.toJSONString(lists); System.out.println(s); } }
[ { "grade": "xx", "name": "xxx", "id": num, "age": num, "hobby": "x" }, ... , { "grade": "xx", "name": "xxx", "id": num, "age": num, "hobby": "xx" } ]
tip
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。