当前位置:网站首页 > Vue.js开发 > 正文

map转jsonobject对象(map转对象 jsonobject.fromobject)



JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(​key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。

pom.xml

 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>

1.通过原生生成json数据格式。

 JSONObject zhangsan = new JSONObject(); try { //添加 zhangsan.put("name", "张三"); zhangsan.put("age", 18.4); zhangsan.put("birthday", "1900-20-03"); zhangsan.put("majar", new String[] {"哈哈","嘿嘿"}); zhangsan.put("null", null); zhangsan.put("house", false); System.out.println(zhangsan.toString()); } catch (JSONException e) { e.printStackTrace(); }

2.通过hashMap数据结构生成

 HashMap<String, Object> zhangsan = new HashMap<>(); zhangsan.put("name", "张三"); zhangsan.put("age", 18.4); zhangsan.put("birthday", "1900-20-03"); zhangsan.put("majar", new String[] {"哈哈","嘿嘿"}); zhangsan.put("null", null); zhangsan.put("house", false); System.out.println(new JSONObject(zhangsan).toString());

3.通过实体生成 

 Student student = new Student(); student.setId(1); student.setAge("20"); student.setName("张三"); //生成json格式 System.out.println(JSON.toJSON(student)); //对象转成string String stuString = JSONObject.toJSONString(student);

4.JSON字符串转换成JSON对象

String studentString = "{"id":1,"age":2,"name":"zhang"}"; //JSON字符串转换成JSON对象 JSONObject jsonObject1 = JSONObject.parseObject(stuString); System.out.println(jsonObject1);

5.list对象转listJson

ArrayList<Student> studentLsit = new ArrayList<>(); Student student1 = new Student(); student1.setId(1); student1.setAge("20"); student1.setName("asdasdasd"); studentLsit.add(student1); Student student2 = new Student(); student2.setId(2); student2.setAge("20"); student2.setName("aaaa:;aaa"); studentLsit.add(student2); //list转json字符串 String string = JSON.toJSON(studentLsit).toString(); System.out.println(string); //json字符串转listJson格式 JSONArray jsonArray = JSONObject.parseArray(string); System.out.println(jsonArray); 

 

到此这篇map转jsonobject对象(map转对象 jsonobject.fromobject)的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!

版权声明


相关文章:

  • vue安装router命令(vue-router安装)2025-02-19 18:18:07
  • vue安装使用(vue的安装和使用)2025-02-19 18:18:07
  • 我的世界加快时间的指令(我的世界加快时间指令1.7.10)2025-02-19 18:18:07
  • vue2与vue3哪个用的多(vue3和2区别)2025-02-19 18:18:07
  • (pl.)是什么意思(play是什么意思翻译成中文翻译)2025-02-19 18:18:07
  • Vue安装脚手架(vue安装脚手架3.0用管理员)2025-02-19 18:18:07
  • swagger2.0访问路径(swagger的访问)2025-02-19 18:18:07
  • map转json数组(map转成json字符串)2025-02-19 18:18:07
  • nvme接口引脚定义(nvme2.0接口)2025-02-19 18:18:07
  • pcie5.0能插pcie4.0么(pcie 5.0 和pcie 4区别)2025-02-19 18:18:07
  • 全屏图片