當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Jackson 读写 JSON
生活随笔
收集整理的這篇文章主要介紹了
Jackson 读写 JSON
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ObjectMapper 提供了下面的 readValue 方法,幫助我們很方便的從不同的數據源讀取對象。
readValue(String src, ...) readValue(File src, ...) readValue(URL src, ...) readValue(InputStream src, ...) readValue(DataInput src, ...) readValue(Reader src, ...) readValue(byte[] src, ...)ObjectMapper 也提供了下面的 writeValue 方法,幫助我們很方便的將對象輸出到不同的目的地。
writeValueAsString(...) writeValue(File desc, ...) writeValue(File desc, ...) writeValue(OutSteam desc, ...) writeValue(DataOutput desc, ...) writeValue(Writer desc, ...) writeValueAsBytes(...)我們還可以讀取 JSON 到數組(Array),列表(List)和映射(Map)中,下面是三個簡答的例子。
package shangbo.jackson.demo2; import com.fasterxml.jackson.databind.ObjectMapper; public class App {public static void main(String[] args) throws Exception {// 實例化 ObjectMapper 對象ObjectMapper objectMapper = new ObjectMapper();// json 消息String json = "[{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}, {\"firstname\":\"San\",\"lastname\":\"Zhang\"}]";// 將 json 轉成數組Person[] people = objectMapper.readValue(json, Person[].class);for(Person p: people) {System.out.println(p);}} } package shangbo.jackson.demo3;import java.util.List;import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper;public class App {public static void main(String[] args) throws Exception {// 實例化 ObjectMapper 對象ObjectMapper objectMapper = new ObjectMapper();// json 消息String json = "[{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}, {\"firstname\":\"San\",\"lastname\":\"Zhang\"}]";// 將 json 轉成列表List<Person> people = objectMapper.readValue(json, new TypeReference<List<Person>>(){});for(Person p: people) {System.out.println(p);}} } package shangbo.jackson.demo4;import java.util.Map;import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper;public class App {public static void main(String[] args) throws Exception {// 實例化 ObjectMapper 對象ObjectMapper objectMapper = new ObjectMapper();// json 消息String json = "{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}";// 將 json 轉成映射Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});System.out.println(map);} }原文鏈接:https://blog.csdn.net/shangboerds/article/details/90543494
總結
以上是生活随笔為你收集整理的Jackson 读写 JSON的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年移动广告优化师发展白皮书
- 下一篇: Jackson 配置 ObjectMap