json字符串解析與類型轉換示例
HTTP請求的返回值通常是以json字符串的形式,服務端在接收到返回值時,需要解析返回值得到想要的結果,包括狀態碼、數據等。這裏介紹一下如何解析json字符串,獲取其中的參數,以及將某個參數轉換成複雜的List<Comment>
這樣的類型。
需要使用jar包:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier> <!-- 必須加上這個,否則無法找到JSONObject類 -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <!-- ObjectMapper所在的jar包,是爲了將JSONObject直接轉換成想要的java對象 -->
</dependency>
下面是示例代碼,分別將json字符串轉換成JSONObject、從JSONObject中獲取參數、將JSONObject轉換成map、將JSONObject裏的參數轉換成List。
json字符串轉換爲JSONObject
public static String parseStrFromJson(JSONObject jsonObject, String key) {
return jsonObject.getString(key);
}
將JSONObject轉換成map
public static String parseStrFromJson(JSONObject jsonObject, String key) {
return jsonObject.getString(key);
}
從JSONObject中獲取某個參數
public static String parseStrFromJson(JSONObject jsonObject, String key) {
return jsonObject.getString(key);
}
將JSONObject中的某個參數轉換成List
private static List<Comment> parseListFromJson(JSONObject jsonObject, String key) {
JSONArray jsonArray = jsonObject.getJSONArray(key);
List<Comment> commentList = new ArrayList<>();
//commentList = (List<Comment>)jsonArray; // 強制轉換類型雖然可以成功,但是List裏的對象將變成JSONObject而不是想要的Comment類型
// 如果使用強制轉換,那麼在for-each語句中將會報錯net.sf.json.JSONObject cannot be cast to com.example.study.demo.beans.Comment
if (jsonArray != null && jsonArray.size() > 0) {
ObjectMapper objectMapper = new ObjectMapper(); // 需要另外導入jar包:jackson-databind
for (Object obj : jsonArray) {
try {
Comment comment = objectMapper.readValue(JSONObject.fromObject(obj).toString(), Comment.class);
commentList.add(comment);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return commentList;
}
源代碼
package com.example.study.demo.http;
import com.example.study.demo.beans.Comment;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* json字符串解析與類型轉換示例
*/
public class JsonParseTest {
/**
* 將json類型的字符串轉換成json對象
* @param jsonStr
* @return
*/
public static JSONObject parseStrToJsonObj(String jsonStr) {
return JSONObject.fromObject(jsonStr);
}
/**
* 根據key,以String的形式獲取對應字段的值
* @param jsonObject
* @param key
* @return
*/
public static String parseStrFromJson(JSONObject jsonObject, String key) {
return jsonObject.getString(key);
}
/**
* 將json對象轉換成map
* @param jsonObject
* @return
*/
private static Map<String,String> parseMapFromJson(JSONObject jsonObject) {
return (Map<String, String>)jsonObject;
}
/**
* 將某個key對應的值轉換成List<Comment>
* @param jsonObject
* @param key
* @return
*/
private static List<Comment> parseListFromJson(JSONObject jsonObject, String key) {
JSONArray jsonArray = jsonObject.getJSONArray(key);
List<Comment> commentList = new ArrayList<>();
//commentList = (List<Comment>)jsonArray; // 強制轉換類型雖然可以成功,但是List裏的對象將變成JSONObject而不是想要的Comment類型
// 如果使用強制轉換,那麼在for-each語句中將會報錯net.sf.json.JSONObject cannot be cast to com.example.study.demo.beans.Comment
if (jsonArray != null && jsonArray.size() > 0) {
ObjectMapper objectMapper = new ObjectMapper(); // 需要另外導入jar包:jackson-databind
for (Object obj : jsonArray) {
try {
Comment comment = objectMapper.readValue(JSONObject.fromObject(obj).toString(), Comment.class);
commentList.add(comment);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return commentList;
}
public static void main(String[] args) {
// 某http接口返回的json格式的數據
String str = "{\"code\":\"200\",\"msg\":\"OK\"," +
"\"data\":[{\"commentId\":\"289389291\",\"newsId\":\"DSQ8CB7G0001875P\",\"content\":\"呵呵呵,還有約炮約出來打牌的,\",\"author\":\"溼人小冰\",\"releaseTime\":1538125092000,\"url\":\"https://news.163.com/18/0928/16/DSQ8CB7G0001875P.html\",\"sourceId\":8446,\"params\":\"a2869674571f77b5a0867c3d71db5856\",\"vote\":66},{\"commentId\":\"289485529\",\"newsId\":\"DSQ8CB7G0001875P\",\"content\":\"想起我表弟,一個在浙江做門的回到家裏結婚生子,回家創業做門生意,老實巴交的人,父母也很貧窮,我們都爲他這個兒子感到高興。 好好的生意不去做,去給賭場放哨,一天幾百塊 後來負載26萬跑路,親戚10多萬,賭場高利貸10多萬。妻離子散,父母都是淚\",\"author\":\"用心做好產品振興中國製造\",\"releaseTime\":1538127470000,\"url\":\"https://news.163.com/18/0928/16/DSQ8CB7G0001875P.html\",\"sourceId\":8446,\"params\":\"a2869674571f77b5a0867c3d71db5856\",\"vote\":27},{\"commentId\":\"290271813\",\"newsId\":\"DSQ8CB7G0001875P\",\"content\":\"什麼意思?讀不懂\",\"author\":\"王氏s1jy\",\"releaseTime\":1538188295000,\"url\":\"https://news.163.com/18/0928/16/DSQ8CB7G0001875P.html\",\"sourceId\":8446,\"params\":\"a2869674571f77b5a0867c3d71db5856\",\"vote\":2}]" +
",\"currentPage\":1,\"commentNum\":5}";
JSONObject jsonObject = parseStrToJsonObj(str);
String code = parseStrFromJson(jsonObject, "code"); // 獲取String
System.out.println("code:" + code);
System.out.println("-----分隔符----");
Map<String, String> map = parseMapFromJson(jsonObject); // 將json對象轉換成map
System.out.println(map.get("msg"));
System.out.println("-----分隔符----");
List<Comment> commentList = parseListFromJson(jsonObject, "data");
if (commentList != null && commentList.size() > 0) {
for (Comment c : commentList) {
System.out.println(c.getCommentId() + ":"+ c.getAuthor());
}
}
System.out.println("....");
}
}
執行結果
Connected to the target VM, address: '127.0.0.1:53719', transport: 'socket'
code:200
-----分隔符----
OK
-----分隔符----
Disconnected from the target VM, address: '127.0.0.1:53719', transport: 'socket'
289389291:溼人小冰
289485529:用心做好產品振興中國製造
290271813:王氏s1jy
....
Process finished with exit code 0