您的位置:首页 > 编程语言 > Java开发

【json】使用json和java对象的序列化和反序列化

2017-11-10 23:50 956 查看
TOC

[[TOC]]

依赖

fastxml

Jackson 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"}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: