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

map转jsonobject对象(map转对象 jsonobject.fromobject)p p JSONObject 只是一种数据结构 可以理解为 JSON 格式的数据结构 key value 结构 可以使用 put 方法给 json 对象添加元素 JSONObject 可以很方便的转换成字符串 也可以很方便的把其他对象转换成 JSONObject 对象 pom xml lt dependency gt lt

大家好,我是讯享网,很高兴认识大家。



 <p></p> 

讯享网

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

pom.xml

讯享网 &lt;dependency&gt; &lt;groupId&gt;com.alibaba&lt;/groupId&gt; &lt;artifactId&gt;fastjson&lt;/artifactId&gt; &lt;version&gt;1.2.28&lt;/version&gt; &lt;/dependency&gt;

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&lt;String, Object&gt; zhangsan = new HashMap&lt;&gt;(); 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&lt;Student&gt; studentLsit = new ArrayList&lt;&gt;(); 
讯享网 Student student1 &#61; new Student(); student1.setId(1); student1.setAge(&#34;20&#34;); student1.setName(&#34;asdasdasd&#34;); studentLsit.add(student1); Student student2 &#61; new Student(); student2.setId(2); student2.setAge(&#34;20&#34;); student2.setName(&#34;aaaa:;aaa&#34;); studentLsit.add(student2); //list转json字符串 String string &#61; JSON.toJSON(studentLsit).toString(); System.out.println(string); //json字符串转listJson格式 JSONArray jsonArray &#61; JSONObject.parseArray(string); System.out.println(jsonArray); 

 

小讯
上一篇 2025-04-29 18:35
下一篇 2025-04-27 08:35

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/197520.html