Json简介
JSON 是一种文本形式的数据交换格式,它比XML更轻量、比二进制容易阅读和编写,调式也更加方便;解析和生成的方式很多,Java中最常用的类库有:JSON-Java、Gson、Jackson、FastJson等
需要注意的一点:json同级别的最后一个元素后不加逗号,
本文以Gson为例,介绍操作Json数据的方法。
[] 中间 代表是一个数组
{} 中间 是一个对象
"key" : "Value" 代表一个键值对
Json数据:主要以以{} 和键值对组成
{
"resultcode": "200",
"reason": "successed!",
"result": {
"today": {
"temperature": "16℃~27℃",
"weather": "阴转多云",
"wind": "西南风3-4 级",
"week": "星期四"
},
"future": [
{
"temperature": "16℃~27℃",
"weather": "阴转多云",
"wind": "西南风3-4 级",
"week": "星期四",
"date": "20150604"
},
{
"temperature": "23℃~35℃",
"weather": "多云转阴",
"wind": "西南风3-4 级",
"week": "星期六",
"date": "20150606"
},
{
"temperature": "20℃~33℃",
"weather": "多云",
"wind": "北风微风",
"week": "星期日",
"date": "20150607"
}
]
},
"error_code": 0
}
解析Json
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class ReadJson {
public static void main(String []args) {
JsonParser parse = new JsonParser();
try {
// 初始化json文件
JsonObject json = (JsonObject) parse.parse(new FileReader("weather.json"));
//获取并输出键值对
System.out.println("resultcode:" + json.get("resultcode").getAsInt());
System.out.println("reason:" + json.get("reason").getAsString());
//获取并Json对象,再获取Json对象内的键值对
JsonObject result = json.get("result").getAsJsonObject();
JsonObject today = result.get("today").getAsJsonObject();
System.out.println("weak:" + today.get("week").getAsString());
System.out.println("weather:" + today.get("weather").getAsString());
} catch (JsonIOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JsonSyntaxException e){
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
解析JsonArray[]
import com.google.gson.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class ReadJsonArray {
public static void main(String []args) {
JsonParser parse = new JsonParser();
try {
//得到JsonArray : futureArray
JsonObject json = (JsonObject)parse.parse(new FileReader("weather.json"));
JsonObject result = json.get("result").getAsJsonObject();
JsonArray futureArray = result.get("future").getAsJsonArray();
for (int i = 0; i < futureArray.size(); ++i) {
JsonObject subObj = futureArray.get(i).getAsJsonObject();
System.out.println("------");
System.out.println("week:" + subObj.get("week").getAsString());
System.out.println("weather:" + subObj.get("weather").getAsString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
注意:文件路径相对路径是从工程根目录开始
FastJson
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。
pom依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
防止中文乱码: 在SpringMVC配置文件中更改 <mvc:annotation-driven/>
<mvc:annotation-driven>
<!--当仅仅传递字符串到前端时,设置数据格式-->
<!--为返回加入响应头 Content-Type: text/html;charset=UTF-8 -->
<!--相同方式是 @RequestMapping(value = "/b",produces="text/html;charset=UTF-8") -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
常用方法
System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);
System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1 = JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);