Json字符串与Object对象相互转换的几种方式
在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML、JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好,下面先看下JSON的格式,一种是对象格式的,另一种是数组对象。
String str = "{'name':'亚索','age':'24','性别':'男'}";//对象
String str2 = "[{\"name\":\"剑圣\",\"age\":25},{\"name\":\"赵信\",\"age\":\"22\"}]";//数组
从上面的两种格式可以看出对象格式和数组对象格式唯一的不同则是在对象格式的基础上加上了[],再来看具体的结构,可以看出都是以键值对的形式出现的,中间以英文状态下的逗号(,)分隔。
在前端和后端进行数据传输的时候这种格式也是很受欢迎的,后端返回json格式的字符串,前台使用js中的JSON.parse()方法把JSON字符串解析为json对象,然后进行遍历,供前端使用。
引入JSON转换需要的依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
JSON字符串转对象
JSONObject jsonObject = JSONObject.parseObject();
对象格式转换,即可获取属性值。
public static void test(String str){
JSONObject jsonObject = JSONObject.parseObject(str);
String name = jsonObject.getString("name");
Integer age = jsonObject.getInteger("age");
System.out.println(age);
System.out.println(jsonObject.toJSONString());
}
JSONArray jsonArray = JSONArray.fromObject();
数组格式转换,先转成JSON数组,然后下标取JSON对象值,最后转换成java对象即可。
public static void test1(String string) {
JSONArray jsonArray = JSONArray.fromObject(string);
Object o = jsonArray.get(0);
net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(o);
String name = jsonObject1.getString("name");
Object o1 = jsonArray.get(1);
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(o1);
int age = jsonObject.getInt("age");
System.out.println(age);
}
java对象转json
student有name,age两字段
Student student = new Student("张三",22);
JSONObject json = JSONObject.fromObject(student);//使用JSONObject
JSONArray array=JSONArray.fromObject(student);//使用JSONArray
打印的结果:json:{"age":"22","name":"张三}
array:[{"age":"22","name":"张三"}]
从结果中可以看出两种方法都可以把java对象转化为JSON字符串,只是转化后的结构不同。