• About
  • Advertise
  • Privacy & Policy
  • Contact
Tech News, Magazine & Review WordPress Theme 2017
  • Home
  • Computers
  • Games
  • Internet
  • Image
  • Top downloads
No Result
View All Result
  • Home
  • Computers
  • Games
  • Internet
  • Image
  • Top downloads
No Result
View All Result
Flickroom
No Result
View All Result
Home Others

Jackson JSON Views | Flickroom

Share on FacebookShare on Twitter

Contents

  • 1 1. Overview
  • 2 2. Serialize Using JSON Views
  • 3 3. Use Multiple JSON Views
  • 4 4. Deserialize Using JSON Views
  • 5 5. Customize JSON Views
  • 6 6. Using JSON Views With Spring
  • 7 7. Conclusion
    • 7.1 Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
    • 7.2 Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Overview

In this tutorial, we ‘ll go over how to use Jackson JSON Views to serialize/deserialize objects, customize the views and finally – how to start integrating with Spring .

2. Serialize Using JSON Views

first – let ‘s go through a dim-witted case – serialize an object with @JsonView.

Reading: Jackson JSON Views | Flickroom

here is our see :

public class Views {
    public static class Public {
    }
}

And the “ User ” entity :

public class User {
    public int id;

    @JsonView(Views.Public.class)
    public String name;
}

now let ‘s serialize a “ User ” exemplify using our watch :

@Test
public void whenUseJsonViewToSerialize_thenCorrect() 
  throws JsonProcessingException {
 
    User user = new User(1, "John");

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    String result = mapper
      .writerWithView(Views.Public.class)
      .writeValueAsString(user);

    assertThat(result, containsString("John"));
    assertThat(result, not(containsString("1")));
}

Note how, because we ‘re serializing with a specific watch active, we ‘re seeing only the right fields being serialized .
It ‘s besides significant to understand, that – by default – all properties not explicitly marked as being function of a scene, are serialized. We are disabling that behavior with the handy DEFAULT_VIEW_INCLUSION feature .

3. Use Multiple JSON Views

future – permit ‘s see how to use multiple JSON Views – each has different fields as in the adopt case :
here we have to views where Internal extends Public, with the internal watch extending the public one :

public class Views {
    public static class Public {
    }

    public static class Internal extends Public {
    }
}

And here is our entity “ Item ” where only the fields id and name are included in the Public opinion :

public class Item {
 
    @JsonView(Views.Public.class)
    public int id;

    @JsonView(Views.Public.class)
    public String itemName;

    @JsonView(Views.Internal.class)
    public String ownerName;
}

If we use the Public view to serialize – only id and name will be serialized to JSON :

@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")));
}

But if we use the Internal opinion to perform the serialization, all fields will be character of the JSON output signal :

@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"));
}

4. Deserialize Using JSON Views

now – let ‘s see how to use JSON Views to deserialize objects – specifically, a User example :

@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());
}

Note how we ‘re using the readerWithView ( ) API to create an ObjectReader using the given opinion .

5. Customize JSON Views

Read more: How to Change Your IP Address

adjacent – get ‘s see how to customize JSON Views. In the future exemplar – we want to make the User “ appoint ” UpperCase in the serialization resultant role. We will use BeanPropertyWriter and BeanSerializerModifier to customize our JSON position. First – here is the BeanPropertyWriter UpperCasingWriter to transform the User name to upper case :

public class UpperCasingWriter extends BeanPropertyWriter {
    BeanPropertyWriter _writer;

    public UpperCasingWriter(BeanPropertyWriter w) {
        super(w);
        _writer = w;
    }

    @Override
    public void serializeAsField(Object bean, JsonGenerator gen, 
      SerializerProvider prov) throws Exception {
        String value = ((User) bean).name;
        value = (value == null) ? "" : value.toUpperCase();
        gen.writeStringField("name", value);
    }
}

And here is the BeanSerializerModifier to set the User name BeanPropertyWriter with our customs UpperCasingWriter :

public class MyBeanSerializerModifier extends BeanSerializerModifier{

    @Override
    public List changeProperties(
      SerializationConfig config, BeanDescription beanDesc, 
      List beanProperties) {
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = beanProperties.get(i);
            if (writer.getName() == "name") {
                beanProperties.set(i, new UpperCasingWriter(writer));
            }
        }
        return beanProperties;
    }
}

now – lashkar-e-taiba ‘s serialize a User example using the modify Serializer :

@Test
public void whenUseCustomJsonViewToSerialize_thenCorrect() 
  throws JsonProcessingException {
    User user = new User(1, "John");
    SerializerFactory serializerFactory = BeanSerializerFactory.instance
      .withSerializerModifier(new MyBeanSerializerModifier());

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializerFactory(serializerFactory);

    String result = mapper
      .writerWithView(Views.Public.class)
      .writeValueAsString(user);

    assertThat(result, containsString("JOHN"));
    assertThat(result, containsString("1"));
}

6. Using JSON Views With Spring

finally – get ‘s take a promptly look at using JSON views with the Spring Framework. We can leverage the @ JsonView note to customize our JSON answer at the API level .
In the follow model – we used the Public view to respond :

@JsonView(Views.Public.class)
@RequestMapping("/items/{id}")
public Item getItemPublic(@PathVariable int id) {
    return ItemManager.getById(id);
}

The reaction is :

{"id":2,"itemName":"book"}

And when we used the Internal scene as follows :

@JsonView(Views.Internal.class)
@RequestMapping("/items/internal/{id}")
public Item getItemInternal(@PathVariable int id) {
    return ItemManager.getById(id);
}

That was the reaction :

{"id":2,"itemName":"book","ownerName":"John"}

If you want to dive deeply into using the views with spring 4.1, you should check out the Jackson improvements in spring 4.1 .

7. Conclusion

In this quick tutorial, we had a look at the Jackson JSON views and the @ JsonView note. We showed how to use JSON Views to have close-grained control condition over our serialize/deserialize work – using a individual or multiple views.
The complete code for this tutorial can be found over on GitHub .
Spring buttocks

Read more: How Google Docs became the social media of the resistance

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE
Jackson bottomland

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Jackson footer standard

Informant : https://flickroom.net
category : Web Browsers

Related Posts

Conversion of Prefix to Postfix expression – Flickroom

Google Issues Warning For 2 Billion Chrome Users

Conversion of Prefix to Postfix expression – Flickroom

Hidden Google: 10 Fun Search Tricks

Conversion of Prefix to Postfix expression – Flickroom

Here are the best new Safari extensions to download for iOS 15 and iPadOS 15 (Updated)

Conversion of Prefix to Postfix expression – Flickroom

How to Download Apple Safari on Computer and PC?

Conversion of Prefix to Postfix expression – Flickroom

Internet Download Manager for Chrome Extension 2022 (IDM)

Conversion of Prefix to Postfix expression – Flickroom

Google’s Help Documents Aren’t Always Up To Date

No Result
View All Result
Flickroom

Knowledge of science, technology and life

Follow Us

NEWS

  • Niobi
  • 2 Verified Hotel Reviews of Savis Hotel | https://flickroom.net
  • What is the WordPress .htaccess File?
  • How to install VPSSIM – A lightweight but simple control panel right on SSH
No Result
View All Result
  • Home

© 2021 Flickroom.net