【json】使用json和java对象的序列化和反序列化
2017-11-10 23:50
956 查看
TOC
[[TOC]]
Jackson JSON Tutorial
Do-JSON-with-Jackson.pdf-很详细
List
属性上
Ignore Null Fields Globally
[[TOC]]
依赖
fastxmlJackson JSON Tutorial
Do-JSON-with-Jackson.pdf-很详细
Creating Java List from JSON Array String
String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]"; List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
Creating Java Map from JSON String
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
Handling Collections
数组String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]"; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class); // print cars
List
String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]"; ObjectMapper objectMapper = new ObjectMapper(); List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){}); // print cars
Dealing with Unknown Fields on the Class
@JsonIgnoreProperties(ignoreUnknown = true) public class MyDtoIgnoreUnknown { ... }
Ignore Null Fields on the Class
@JsonInclude(Include.NON_NULL) public class MyDto { ... }
属性上
public class MyDto { @JsonInclude(Include.NON_NULL) private String stringValue; private int intValue; // standard getters and setters }
Ignore Null Fields Globally
mapper.setSerializationInclusion(Include.NON_NULL);
Change Name of Field for Serialization
@JsonProperty("strVal") public String getStringValue() { return stringValue; }
Enum as Json Object
@JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum Distance { ... }
Enums and @JsonValue
public enum Distance { ... @JsonValue public String getMeters() { return meters; } }
Use @JsonFormat to format Date
public class Event { public String name; @JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") public Date eventDate; } @Test public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String toParse = "20-12-2014 02:30:00"; Date date = df.parse(toParse); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(event); assertThat(result, containsString(toParse)); }
Serialize Joda-Time with Jackson
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-joda</artifactId> <version>2.4.0</version> </dependency> @Test public void whenSerializingJodaTime_thenCorrect() throws JsonProcessingException { DateTime date = new DateTime(2014, 12, 20, 2, 30, DateTimeZone.forID("Europe/London")); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String result = mapper.writeValueAsString(date); assertThat(result, containsString("2014-12-20T02:30:00.000Z")); }
Serialize Java 8 Date with Jackson
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.4.0</version> </dependency> @Test public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException { LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JSR310Module()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String result = mapper.writeValueAsString(date); assertThat(result, containsString("2014-12-20T02:30")); }
Deserialize Date
@Test public void whenDeserializingDateWithJackson_thenCorrect() throws JsonProcessingException, IOException { String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}"; SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); Event event = mapper.readerFor(Event.class).readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); }
Serialize Using JSON Views
public class Views { public static class Public { } public static class Internal extends Public { } } public class Item { @JsonView(Views.Public.class) public int id; @JsonView(Views.Public.class) public String itemName; @JsonView(Views.Internal.class) public String ownerName; } @Test public void whenUsePublicView_thenOnlyPublicSerialized() throws JsonProcessingException { Item item = new Item(2, "book", "John"); ObjectMapper mapper = new ObjectMapper(); String result = mapper .writerWithView(Views.Public.class) .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); assertThat(result, not(containsString("John"))); } @Test public void whenUseInternalView_thenAllSerialized() throws JsonProcessingException { Item item = new Item(2, "book", "John"); ObjectMapper mapper = new ObjectMapper(); String result = mapper .writerWithView(Views.Internal.class) .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); assertThat(result, containsString("John")); }
Deserialize Using JSON Views
@Test public void whenUseJsonViewToDeserialize_thenCorrect() throws IOException { String json = "{"id":1,"name":"John"}"; ObjectMapper mapper = new ObjectMapper(); User user = mapper .readerWithView(Views.Public.class) .forType(User.class) .readValue(json); assertEquals(1, user.getId()); assertEquals("John", user.getName()); }
Using JSON Views with Spring
@JsonView(Views.Public.class) @RequestMapping("/items/{id}") public Item getItemPublic(@PathVariable int id) { return ItemManager.getById(id); } {"id":2,"itemName":"book"} @JsonView(Views.Internal.class) @RequestMapping("/items/internal/{id}") public Item getItemInternal(@PathVariable int id) { return ItemManager.getById(id); } {"id":2,"itemName":"book","ownerName":"John"}
相关文章推荐
- Jedis和JAVA对象的序列化和反序列化的使用
- 使用Struts 2将Java对象序列化成JSON
- 将java对象存储到redis数据库(使用序列化和反序列化)
- JsonTools(java Json序列化/反序列化)简单使用
- 将java对象存储到redis数据库(使用序列化和反序列化)
- java 使用xom对象数据序列化为xml、反序列化、Preferences相关操作小案例
- 使用Newtonsoft.Json序列化和反序列化对象(源码)
- java对象序列化与反序列化的默认格式和json格式使用示例
- java 常用序列化和反序列化框架使用-json,kyro,jdk
- java使用serializable进行序列化与反序列化实现对象clone(克隆)
- 在MVC中使用Json.Net序列化和反序列化Json对象
- XStream java对象和json文件进行序列化和反序列化
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
- ASP.NET:使用Newtonsoft.Json序列化和反序列化JSON对象的例子
- 【Java】使用Json-lib序列化关联对象的异常解决
- 将java对象存储到redis数据库(使用序列化和反序列化)
- 使用NewtonSoft.JSON.dll来序列化和反序列化对象
- java对象的序列化与反序列化使用
- 使用DataContractJsonSerializer类将类型实例序列化为JSON字符串和反序列化为实例对象
- ASP.NET:使用Newtonsoft.Json序列化和反序列化JSON对象的例子