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"}

【json】使用json和java对象的序列化和反序列化的更多相关文章

  1. Java对象的序列化与反序列化-Json篇

    说到Java对象的序列化与反序列化,我们首先想到的应该是Java的Serializable接口,这玩意在两个系统之间的DTO对象里面可能会用到,用于系统之间的数据传输.或者在RPC(远程方法调用)时可 ...

  2. Java对象的序列化与反序列化

    序列化与反序列化 序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程.一般将一个对象存储至一个储存媒介,例如档案或是记亿体缓冲等.在网络传输过程中,可以是字节或是 ...

  3. Java对象的序列化和反序列化[转]

    Java基础学习总结--Java对象的序列化和反序列化 一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化.把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种用 ...

  4. JSON和XML格式与对象的序列化及反序列化的辅助类

    下面的代码主要是把对象序列化为JSON格式或XML格式等 using System; using System.Collections.Generic; using System.Globalizat ...

  5. 一文带你全面了解java对象的序列化和反序列化

    摘要:这篇文章主要给大家介绍了关于java中对象的序列化与反序列化的相关内容,文中通过详细示例代码介绍,希望能对大家有所帮助. 本文分享自华为云社区<java中什么是序列化和反序列化?>, ...

  6. [转]Java对象的序列化和反序列化

    一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化. 把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种用途: 1) 把对象的字节序列永久地保存到硬盘上,通常存 ...

  7. Java基础学习总结——Java对象的序列化和反序列化

    一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化. 把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种用途: 1) 把对象的字节序列永久地保存到硬盘上,通常存 ...

  8. Java对象的序列化和反序列化

    对象的序列化是指将对象转换为字节序列的过程 对象的反序列化是指将字节序列恢复对象的过程 主要有两种用途: 1.把对象的字节序列永久地保存在硬盘上,通常放在一个文件中. 2.在网络上传输对象的字节序列. ...

  9. java对象的序列化与反序列化使用

    1.Java序列化与反序列化  Java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程. 2.为什么需要序列化与反序列化 我们知道,当两个进程进 ...

  10. Java对象的序列化和反序列化实践

    2013-12-20 14:58 对象序列化的目标是将对象保存在磁盘中,或者允许在网络中直接传输对象.对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久的保存 ...

随机推荐

  1. Spring 注解详细分析解释有实例

    概述 注释配置相对于 XML 配置具有很多的优势: 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作.如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO ...

  2. P2331 [SCOI2005]最大子矩阵 (动规:分类讨论状态)

    题目链接:传送门 题目: 题目描述 这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大.注意:选出的k个子矩阵不能相互重叠. 输入输出格式 输入格式: 第一行为n,m,k( ...

  3. day python calss08 深浅copy

    一  join (格式:   . join) 遍历列表把列表中的每一项用指定符号进行拼接.(把列表转成字符串0 # lst = ["汪峰", "吴君如", &q ...

  4. POJ 3468:A Simple Problem with Integers(线段树区间更新模板)

    A Simple Problem with Integers Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 141093 ...

  5. fedora的选择

    Fedora 首页包含3种版本: 工作站,服务器,ATOMIC 个人只要使用工作站即可,然后,下载界面有另一个选择:Silverblue ========================== Silv ...

  6. 进入网站自动加自己为QQ好友代码

    <meta http-equiv="refresh" content="0; url=tencent://AddContact/?fromId=50&fro ...

  7. linux下寻找段错误的方法

    为了能够快速找到发生段错误的地方,记录以下两种方法. objdump和backtrace的配合使用 :https://www.cnblogs.com/jiangyibo/p/9507555.html ...

  8. LeetCode - Reorganize String

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  9. centos7和linux防火墙配置入门

    linux部分 iptables -L    列出当前防火墙策略 iptables -F   清空防火墙策略 iptables -P INPUT  DROP   默认设置丢弃进来的流量包(-p指默认策 ...

  10. s3c2140 开发板笔记

    文章目录 原理图补充说明 开机串口输出 开发板硬件配置 参考文档 工具下载 代码下载 安装交叉编译器 编译kernel 制作文件系统 配置nfs 配置smb Minimal client-only S ...