標籤:
一個json格式的字串比如:
{"status":10001,"code":"HDkGzI","pubkey":"DBCEEECFD3F6808C85254B1","servertime":1475741518}
,在java中對應的字串為:
"{\"status\":10001,\"code\":\"HDkGzI\",\"pubkey\":\"DBCEEECFD3F6808C85254B1\",\"servertime\":1475741518}"
格式化後:
{
"status": 10001,
"code": "HDkGzI",
"pubkey": "DBCEEECFD3F6808C85254B1",
"servertime": 1475741518
}
有的時候我們想在這個json格式字串中去一項,比如想去出pubkey這一項,
那麼結合jackson這個工具就可以很方便地解決這個問題。
代碼如下:
1 package com.test.javaAPI.json; 2 3 import java.io.IOException; 4 import java.util.Map; 5 6 import org.codehaus.jackson.JsonParseException; 7 import org.codehaus.jackson.map.JsonMappingException; 8 import org.codehaus.jackson.map.ObjectMapper; 9 import org.junit.Test;10 11 import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;12 13 public class JacksonTest2 {14 public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {15 String str = new JacksonTest2().removeJsonObjByKey(UtilJackson.jsonStr4, UtilJackson.jsonStr4_KEY1);16 System.out.println(str);17 }18 19 /**20 * 根據鍵除去json格式字串中的某一個索引值對21 * 22 * @param jsonStr23 * @param key24 * @return25 * @throws IOException26 * @throws JsonMappingException27 * @throws JsonParseException28 */29 public String removeJsonObjByKey(String jsonStr, String key)30 throws JsonParseException, JsonMappingException, IOException {31 ObjectMapper objMap = new ObjectMapper();32 // 1 把json格式字串轉換為 java.util.Map33 Map map = objMap.readValue(jsonStr, Map.class);34 // 2 刪除map中的對應key的項目35 map.remove(key);36 // 準備位元組流,接收ObjectMapper中寫出的輸出資料流37 ByteOutputStream bops = new ByteOutputStream();38 // 3 把map重新轉換為json格式字串39 objMap.writeValue(bops, map);40 if (!"".equals(bops)) {41 return bops.toString();42 }43 return "";44 }45 46 /**47 * 方法的作用:去除一個json格式字串的某一個key 刪除 這個json字串裡的這個key對應的對象 該方法與架構中的 String48 * cn.sinobest.framework.web.his.JsonManager.removeDataPackage(String49 * jsonStr) 這個方法的功能一致50 * 51 * @param jsonKey52 * @return53 * @throws JsonParseException54 * @throws JsonMappingException55 * @throws IOException56 */57 @Test58 public String removeDataPackage(String jsonKey) throws JsonParseException, JsonMappingException, IOException {59 ObjectMapper objMap = new ObjectMapper();60 Map map = objMap.readValue(UtilJackson.jsonStr_HN, Map.class);61 // map.remove("DataPackage");62 map.remove(jsonKey);63 ByteOutputStream bops = new ByteOutputStream();64 objMap.writeValue(bops, map);65 System.out.println(bops.toString());66 return null;67 }68 69 }
其中main方法字串分別為:
1 public static String jsonStr4 = "{\"verified\":false,\"name\":{\"last\":\"Hankcs\",\"first\":\"Joe\"},\"userImage\":\"Rm9vYmFyIQ==\",\"gender\":\"MALE\"}";2 public static String jsonStr4_KEY1 = "verified";
運行後的結果為:
{"name":{"last":"Hankcs","first":"Joe"},"userImage":"Rm9vYmFyIQ==","gender":"MALE"},
而原來的字串jsonStr4為:
{"verified":false,"name":{"last":"Hankcs","first":"Joe"},"userImage":"Rm9vYmFyIQ==","gender":"MALE"}。
jackson的簡單實用執行個體(json)