JSONObject是一种类似于JSON格式的key-value的数据结构,我们可以通过其方法put给JSONObject对象添加key-value格式的字符串,还是比较方便的,后续还可以转换成JSONxxx的其他类型,都是很方便的.
刚刚入坑的公司是SSM框架体系,SpringMVC的相应返回值是Map<String,Object>,所以用的比较频繁,刚入职场的菜鸟我觉得应该还是比较常用的吧
pom文件(依赖/包): 我们使用的版本是:1.2.28,还是根据需要来锁定版本吧
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
bean实体类转换JSONObject:
Emp emp = new Emp();
emp.setId(1);
emp.setName("小张");
//转换
JSONObject jsonObject = JSONObject.parseObject(emp.toString());
原生JSONObject bean对象
//原始的原生代码
//原生的bean对象也是key-value格式的,我们可以就当做是Map集合,只不过是JSON格式的
JSONObject object = new JSONObject();
object.put("A","a");
object.put("B","b");
System.out.println("object = " + object);
普通的字符串转换
//普通String->JSONObject的转换
String str = "逻辑需求";
JSONObject jsonStr = JSONObject.parseObject(str);
list集合转换JSONArray
/list集合转换JSONOArray
//这个也是我们比较常用的
List<Emp> list = new ArrayList<Emp>();
Emp empTwo = new Emp();
empTwo.setId(2);
empTwo.setName("小李");
Emp empThree = new Emp();
empThree.setId(3);
empThree.setName("小王");
Collections.addAll(list,empTwo,empThree);
JSONArray jsonArray = JSONArray.parseArray(list.toString());
JSONArray和JSOnObject的相互转换,也谈不上转换,我们可以理解成容器
//JSONObject&JSONArray的转换
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
//arr->obj的转换,可以响应给前端
JSONObject fluentPut = jsonObj.fluentPut("响应key", jsonArr);
//obj->arr的转换,亦可响应给前段
JSONArray objects = jsonArr.fluentAdd(jsonObj);
JSONObj还是比较常使用的,我刚接触的时候就非常喜欢,我们可以用在返回给前段key-value,或者建立省级联动的json字符串,还是比较方便的,第一次发文章如有错误还请指出,多谢.