标签:JSONObject println JSON 详解 put new zhangsan
JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。
pom:
com.alibaba fastjson 1.2.28 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 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);
标签:JSONObject,println,JSON,详解,put,new,zhangsan 来源: https://blog.csdn.net/weixin_44694660/article/details/118768036
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。