将多个JSON字段映射到单个Java字段

简介

本文中,教大家如何使用Jackson和Gson将不同的JSON字段映射到单个Java字段中。

Maven依赖

为了使用JacksonGson库,我们需要在POM中添加以下依赖项:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
    <scope>test</scope>
</dependency>

示例JSON

假如,我们希望将不同位置的天气细节输入到我们的Java类中。我们发现了一些将天气数据发布为JSON文档的网站。但是,它们的格式并未是一致的

{
    "location": "广州",
    "temp": 15,
    "weather": "多云"
}
{
    "place": "深圳",
    "temperature": 35,
    "outlook": "晴天"
}

我们希望将这两种格式反序列化为同一个Java类,名为 Weather:

使用Jackson

为实现这一目标,我们将使用Jackson的@JsonProperty和@JsonAlias注释。这两个注解将帮助我们把JSON属性映射到同一Java字段。

首先,我们将使用@JsonProperty注释,以便让Jackson知道要映射的JSON字段的名称。在值@JsonProperty注解同时用于反序列化和序列化。

然后我们可以使用@JsonAlias注释。因此,Jackson将知道JSON文档中映射到Java字段的其他字段的名称。在用了@JsonAlias注释的属性用于反序列化。

@JsonProperty("location")
@JsonAlias("place")
private String location;
@JsonProperty("temp")
@JsonAlias("temperature")
private int temp;
 
@JsonProperty("outlook")
@JsonAlias("weather")
private String outlook;

Getter、Setter忽略

现在我们已经添加了注释,让我们使用Jackson的ObjectMapper方法创建Weather对象。

@Test
public void test() throws Exception {
 
    ObjectMapper mapper = new ObjectMapper();
 
    Weather weather = mapper.readValue("{\n" 
      + "  \"location\": \"广州\",\n"
      + "  \"temp\": 15,\n"
      + "  \"weather\": \"多云\"\n"
      + "}", Weather.class);
 
    TestCase.assertEquals("广州", weather.getLocation());
        TestCase.assertEquals("多云", weather.getOutlook());
        TestCase.assertEquals(15, weather.getTemp());
 
    weather = mapper.readValue("{\n"
      + "  \"place\": \"深圳\",\n"
      + "  \"temperature\": 35,\n"
      + "  \"outlook\": \"晴天\"\n"
      + "}", Weather.class);
 
   TestCase.assertEquals("深圳", weather.getLocation());
        TestCase.assertEquals("晴天", weather.getOutlook());
        TestCase.assertEquals(35, weather.getTemp());
}

使用Gson

现在,我们来看看Gson如何实现。我们需要在@SerializedName注释中使用值和 备用参数。

第一个将用作默认值,而第二个将用于指示我们要映射的JSON字段的备用名称:

@SerializedName(value="location", alternate="place")
private String location;
@SerializedName(value="temp", alternate="temperature")
private int temp;
 
@SerializedName(value="outlook", alternate="weather")
private String outlook;

现在我们已经添加了注释,让我们测试一下我们的例子:


@Test
public void test() throws Exception {
         
    Gson gson = new GsonBuilder().create();
    Weather weather = gson.fromJson("{\n"
      + "  \"location\": \"广州\",\n"
      + "  \"temp\": 15,\n"
      + "  \"weather\": \"多云\"\n"
      + "}", Weather.class);
         
    TestCase.assertEquals("广州", weather.getLocation());
        TestCase.assertEquals("多云", weather.getOutlook());
        TestCase.assertEquals(15, weather.getTemp());
         
    weather = gson.fromJson("{\n"
      + "  \"place\": \"深圳\",\n"
      + "  \"temperature\": 35,\n"
      + "  \"outlook\": \"晴天\"\n"
      + "}", Weather.class);
        
      TestCase.assertEquals("深圳", weather.getLocation());
        TestCase.assertEquals("晴天", weather.getOutlook());
        TestCase.assertEquals(35, weather.getTemp());
         
}

结论

我们通过使用Jackson的@JsonAlias或Gson的替代参数看到了这一点,我们可以轻松地将不同的JSON格式转换为相同的Java对象。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.概述2.Gson的目标3.Gson的性能和扩展性4.Gson的使用者5.如何使用Gson 通过Maven来使用...
    人失格阅读 14,414评论 2 18
  • 概况 Gson是一个Java库,它可以用来把Java对象转换为JSON表达式,也可以反过来把JSON字符串转换成与...
    木豚阅读 6,872评论 0 2
  • 在一个方法内部定义的变量都存储在栈中,当这个函数运行结束后,其对应的栈就会被回收,此时,在其方法体中定义的变量将不...
    Y了个J阅读 4,464评论 1 14
  • 概述 Moshi是Square公司在2015年6月开源的有关Json的反序列化及序列化的框架,说到Json,大家应...
    wustor阅读 13,037评论 7 33
  • 五一假期第一天,在家做了一天手作,低头低了一天,整个肩膀各种不舒服。还有一个总会给我帮倒忙的家伙,我在干活的...
    清浅_精油疗法康复理疗师阅读 208评论 3 7