赞
踩
JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。
pom(本文所有代码仅使用这一个依赖即可):
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.12</version>
</dependency>
</dependencies>
- import com.alibaba.fastjson.JSONException;
- import com.alibaba.fastjson.JSONObject;
-
- public class Demo {
- public static void main(String[] args) {
-
- 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();
- }
-
- }
- }
- import com.alibaba.fastjson.JSONObject;
-
- import java.util.HashMap;
-
- public class Demo {
- public static void main(String[] args) {
-
- 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());
-
- }
- }
需要自定定义实体(例子中实体名为Student),目前本人水平有限,不清楚,日后有机会再完善。
- import com.alibaba.fastjson.JSONObject;
-
- public class Demo {
- public static void main(String[] args) {
-
- 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);
-
- }
- }
- import com.alibaba.fastjson.JSONObject;
-
- public class Demo {
- public static void main(String[] args) {
-
- String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";
-
- //JSON字符串转换成JSON对象
- JSONObject jsonObject1 = JSONObject.parseObject(studentString);
-
- System.out.println(jsonObject1);
-
- }
- }
需要自定定义实体(例子中实体名为Student),目前本人水平有限,不清楚,日后有机会再完善。
- import com.alibaba.fastjson.JSONObject;
-
- public class Demo {
- public static void main(String[] args) {
-
- 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);
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。