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. GitHub教程手册、使用流程

    简述GitHub的使用方法 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请调整网页缩放比例至200%) 1 注册过GitHub的朋友, ...

  2. django安装命令

    通过pip安装Django   ==指定版本号 pip install Django==2.0.2 查看djangoshifou安装成功:1.进入python ,2.import   django 查 ...

  3. day04之流程控制

    if语句: if 条件1: pass elif 条件2: pass elif 条件3: pass else: pass if 条件语句中,先判断条件1,如果满足条件1,则执行第二行代码,第二行执行完后 ...

  4. lesson7-图像描述 -小象cv

    2018-04-25朴素rcnn - 梯度消失严重LSTM长短时记忆模型,有效捕捉长时记忆包含四个神经元组:一个记忆神经元三个控制门神经元:输入.忘记.输出 注意:输入调制门.输出调制门 3个输入:前 ...

  5. python django day 3 页面,自动 跳转,参数传递

    zqxt_views/urls.pypath('', calc_views.index, name='home'), calc/views.pydef index(request): return r ...

  6. url参数和字典的相互转化

    目标url:https://www.baidu.com/s?&wd=python&ie=utf-8 将字典转成url参数 使用urllib.parse的urlencode方法,将字典对 ...

  7. C++ 作业(哈夫曼树)

    #include<bits/stdc++.h> #define fi first #define se second #define int long long using namespa ...

  8. hihocoder1489 Legendary Items 概率期望

    Little Hi is playing a video game. Each time he accomplishes a quest in the game, Little Hi has a ch ...

  9. hdu4965 Fast Matrix Calculation 矩阵快速幂

    One day, Alice and Bob felt bored again, Bob knows Alice is a girl who loves math and is just learni ...

  10. hdu4292 Food 最大流

    You, a part-time dining service worker in your college’s dining hall, are now confused with a new pr ...