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. directive例子2

    (function() { angular.module('app.widgets') .directive('bsModalPlus', function($window, $sce, $modal ...

  2. Unity 3D调用Windows打开、保存窗口、文件浏览器

    Unity调用Window窗口 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分 ...

  3. poj 2253——Frogger

    这个题一开始不知道咋做,但是大致有点意思.后来还是借鉴了题解发现可以用dijkstra,不太理解.但是在最后自己推的时候突然理解了. dijkstra应该也算是动态规划.我们用dis[i]数组作为青蛙 ...

  4. java list 的遍历

    import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.I ...

  5. Tomcat介绍、安装jdk、安装Tomcat、配置Tomcat监听80端口

    1.Tomcat介绍 2.安装jdk下载:wget -c http://download.oracle.com/otn-pub/java/jdk/10.0.1+10/fb4372174a714e6b8 ...

  6. 03 事务,连接池DBCP,C3P0,DBUtils

    事务 Transaction  其实指的一组操作,里面包含许多个单一的逻辑.只要有一个逻辑没有执行成功,那么都算失败. 所有的数据都回归到最初的状态(回滚) 事务的作用:为了确保逻辑的成功. 例子: ...

  7. 实验吧—Web——WP之 猫抓老鼠

    打开解题链接后,发现他是让我们输入key提交查询就能进行下一步 题目中提示了:catch(抓的意思) 那么我们很容易就能想到是BP抓包,抓包后直接放到repeater中改包. 我们先GO一下看看有什么 ...

  8. Project Euler 54

    #include<bits/stdc++.h> using namespace std; ]; ]; ; map<char,int> mp; //map<char,cha ...

  9. 世界各个地区WIFI 2.4G及5G信道划分表(附无线通信频率分配表)

    参考:https://blog.csdn.net/dxpqxb/article/details/80969760 目前主流的无线WIFI网络设备802.11a/b/g/n/ac: 传统 802.11 ...

  10. Why service collaboration needs choreography AND orchestration

    转自:https://blog.bernd-ruecker.com/why-service-collaboration-needs-choreography-and-orchestration-239 ...