Android 基本 Jackson Marshalling/Unmarshalling

本文内容

  • 基本 Jack Marshalling
    • 忽略属性
    • 忽略 Null 字段
    • 改变字段名字
  • 基本 Jackson Marshalling
    • 把 JSON 解析成 JsonNode
    • 带无法识别的属性的 Unmarshalling json
  • 参考资料
  • 术语

 

基本 Jackson Marshalling



如何把一个 Java 实体序列化(serialize)成一个 JSON 字符串,并且如何控制映射的过程,以便达到准确的你想要的 JSON 格式。

忽略属性

当 Jackson 默认值不够,我们就需要准确地控制序列化什么成 JSON,此时非常有用。有很多方式来忽略属性。

  • 在类的级别上忽略字段(field)

通过使用 @JsonIgnoreProperties 注解(annotation)和指定字段名字,我们可以在类的级别上忽略指定的字段:

@JsonIgnoreProperties(value = { "intValue" })
public class MyDto {
 
    private String stringValue;
    private int intValue;
    private boolean booleanValue;
 
    public MyDto() {
        super();
    }
 
    // standard setters and getters are not shown
}

现在测试一下,对象被写成 JSON 后,intValue 字段没有输出:

@Test
public void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();
 
    String dtoAsString = mapper.writeValueAsString(dtoObject);
 
    assertThat(dtoAsString, not(containsString("intValue")));
}
  • 在字段的级别上忽略字段

We can also ignore a field directly via the @JsonIgnore annotation directly on the field:

public class MyDto {
 
    private String stringValue;
    @JsonIgnore
    private int intValue;
    private boolean booleanValue;
 
    public MyDto() {
        super();
    }
 
    // standard setters and getters are not shown
}

We can now test that the intValue field is indeed not part of the serialized json output:

@Test
public void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();
 
    String dtoAsString = mapper.writeValueAsString(dtoObject);
 
    assertThat(dtoAsString, not(containsString("intValue")));
}
  • Ignore all fields by type

Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType anotation. If we control the type, then we can annotate the class directly:

@JsonIgnoreType
public class SomeType { ... }

More often than not however, we don’t have control of the class itself; in this case, we can make good use of Jackson mixins.

First, we define a MixIn for the type we’d like to ignore, and annotate that with @JsonIgnoreType instead:

@JsonIgnoreType
public class MyMixInForString {
    //
}

Then we register that mixin to replace (and ignore) all String types during marshalling:

mapper.addMixInAnnotations(String.class, MyMixInForString.class);

At this point, all Strings will be ignored instead of marshalled to json:

@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixInAnnotations(String.class, MyMixInForString.class);
    MyDto dtoObject = new MyDto();
    dtoObject.setBooleanValue(true);
 
    String dtoAsString = mapper.writeValueAsString(dtoObject);
 
    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}
  • Ignore fields using Filters

Finally, we can also use Filters to ignore specific fields in Jackson. First, we need to define the filter on the java object:

@JsonFilter("myFilter")
public class MyDtoWithFilter { ... }

Then, we define a simple filter that will ignore the intValue field:

SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);

Now we can serialize the object and make sure that the intValue field is not present in the json output:

@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
    FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
 
    MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
 
    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}

he article illustrated how to ignore fields on serialization – first by name, then directly, and finally – we ignored the entire java type with MixIns and we use filters for more control of the output.

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

 

忽略 Null 字段

改变字段名字

 

基本 Jackson Unmarshalling



说明如何把一个 JSON 字符串反序列(deserialize)化成一个 Java 实体。无论 JSON 多么“怪异”,我们需要把它映射成一个已定义的 Java 实体类。

把 JSON 解析成 JsonNode

带未识别属性的 Unmarshalling json

 

参考资料


 

术语


Marshalling/Unmarshalling

marshalling 是把一个对象的内存描述转换成适合存储或传输的一个数据格式的过程,它通常用于,数据必须在一个计算机程序的不同部分之间,从一个程序移动到另一个。Marshalling 类似于 serialization,用于一个对象跟远程对象通信,在这种情况下,是一个被序列化的对象。这简化了复杂的通信,使用自定义、复杂的对象通信,而不是基本数据类型。与 marshalling 相对的,或逆过程,称为 unmarshalling(demarshalling,类似于 deserialization)。

在 Python 里,marshal 跟 serialize 是一个概念,但是在 Java 中却不是。

参看 http://en.wikipedia.org/wiki/Unmarshalling#Comparison_with_serialization

Android 基本 Jackson Marshalling/Unmarshalling,布布扣,bubuko.com

时间: 2024-10-07 05:19:23

Android 基本 Jackson Marshalling/Unmarshalling的相关文章

Android 高级 Jackson Marshalling(serialize)/Unmarshalling(deserialize)

本文内容 高级 Jackson Marshalling Serialize Only Fields that meet a Custom Criteria with Jackson Serialize Enums as JSON Objects JsonMappingException (No serializer found for class) Jackson – Custom Serializer 高级 Jackson Unmarshalling Unmarshall to Collect

Jackson 概述

原文地址 本文内容 JSON 的三种方式 示例 Full Data Binding (POJO) 示例 "Raw" Data Binding 示例 用泛型数据绑定 Tree Model 示例 Streaming API 示例 Streaming API 示例 2: 数组 Next Steps Inspired by the quality and variety of XML tooling available for the Java platform (StAX, JAXB, et

Spring Framework Ecosystem – Introduction to Spring Projects

来自于:http://springtutorials.com/spring-ecosystem/ Hello and Welcome to Spring Tutorials Blog! Is it fair to assume you have at least heard of Spring Framework official website – spring.io? If not, I would recommend that you check it out. There are som

[译] 第三十天:Play Framework - Java开发者梦寐以求的框架 - 百花宫

前言 30天挑战的最后一天,我决定学习 Play Framework .我本来想写Sacla,但是研究几个小时后,我发现没法在一天内公正评价Scala,下个月花些时间来了解并分享经验.本文我们先来看看Play框架基础,再开发个程序. 什么是Play框架? Play 是一个开源的现代web框架,用Java和Scala写可扩展的web程序.它能自动加载更新使得极大提高生产率.Play设计了无状态,非阻塞的架构,这使得用Play框架开发水平扩展web程序很容易. 我为什么关注Play? 我学习Play

kbmmw 5.0 beta1 发布

经过大半年的等待,kbmmw 的新版终于来了.经过近5年的打磨, kbmmw 的版本号升级到5了. kbmMW is a portable, highly scalable, high end application server and enterprise architecture integration (EAI) development framework for Win32, ..Net and Linux with clients residing on Win32, .Net, L

KBMMW 4.81.00 发布

这次更新的速度非常快. 4.81.00 May 9 2015 Important notes (changes that may break existing code) ====================================================== * Changed TkbmMWOnFileAccess event to allow rewriting Path. TkbmMWOnFileAccess = procedure (Sender:TObject; v

APK瘦身记,如何实现高达53%的压缩效果

作者:非戈@阿里聚安全 1.我是怎么思考这件事情的 APK是Android系统安装包的文件格式,关于这个话题其实是一个老生常谈的题目,不论是公司内部,还是外部网络,前人前辈已经总结出很多方法和规律.不过随着移动端技术近两年的飞速发展,一些新的思维方式和优化方法也逐渐涌现和成熟起来.笔者在实践过程中踩过一些坑,收获了一些经验,在这里做个思考和总结,所以随笔给大家,希望对大家从事相关工作的时候有所帮助和参考,同时也是抛砖引玉,希望大家共同探讨这个开放性的话题. 关于为什么APK要瘦身,这个不多说,只

apk瘦身 提高优化效果

APK瘦身记,如何实现高达53%的压缩效果 我是怎么思考这件事情的 APK是Android系统安装包的文件格式,关于这个话题其实是一个老生常谈的题目,不论是公司内部,还是外部网络,前人前辈已经总结出很多方法和规律.不过随着移动端技术近两年的飞速发展,一些新的思维方式和优化方法也逐渐涌现和成熟起来.笔者在实践过程中踩过一些坑,收获了一些经验,在这里做个思考和总结,所以随笔给大家,希望对大家从事相关工作的时候有所帮助和参考,同时也是抛砖引玉,希望大家共同探讨这个开放性的话题. 关于为什么APK要瘦身

android:json解析的两个工具:Gson和Jackson的使用小样例

1.简单介绍 json是android与server通信过程中经常使用的数据格式,比如.例如以下是一个json格式的字符串: {"address":"Nanjing","name":"NUPT","students":[{"name":"stu1","id":"10000","age":20},{"