用Map替代pojo类来装数据
需要用到的依赖!如下:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
- 作用
- 用以转换数据—> map <==> jsonString
代码如下
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;
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");
}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
- 上面json格式化使用了 Notepad++的 JSON viewer插件!
- json为前后端数据交换数据的常用数据格式!
|