Jackson's @JsonView is not functioning properly as per expectations

Currently, I am working with Jackson JSON 1.9.12 in conjunction with SpringMVC. As part of this, I have created a data transfer object (dto) with JSON fields. To have two profiles of the same dto with different JSON fields, I took the approach of creating two interfaces and annotating the fields using the @JsonView annotation.

class Views {
    static class Public {}
    static class ExtendedPublic {}
    ...
}

public class Thing {
    @JsonView(Views.Public.class) Integer id;
    @JsonView(Views.ExtendPublic.class) String name;
}

Within the controller:

@RequestMapping(value = "/thing/{id}")
public void getThing(@PathVariable final String id, HttpServletResponse response) {
    Thing thing = new Thing();
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writerWithView(Views.Public.class).writeValueAsString(thing);
    LOG.debug("JSON: {}", json);
}

The expected result is for the JSON to only include the "id" field, however, it seems to always include all fields.

Does anyone have any suggestions or ideas on how to address this issue?

Answer №1

Tested with Spring 3.2.0 and Jackson 1.9.12, the code below returns {id: 1} instead of the extended version {name: "name"}. This is due to the use of .writerWithView(Views.Public.class). Changing it to Views.ExtendPublic.class will output {"id":1,"name":"name"}

Note: Included all project files for a comprehensive solution, improving upon previous answers found on Using @JsonView with Spring MVC

DemoController.java

package com.demo.app;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.codehaus.jackson.map.annotate.JsonView;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class DemoController {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value="/jsonOutput")
    @ResponseBody
    public String myObject(HttpServletResponse response) throws IOException {
        ObjectWriter objectWriter = objectMapper.writerWithView(Views.Public.class);
        return objectWriter.writeValueAsString(new MyObject());
    }

    public static class Views {
        static class Public {}
        static class ExtendPublic extends Public {}
    }

    public class MyObject {
        @JsonView(Views.Public.class) Integer id = 1;
        @JsonView(Views.ExtendPublic.class) String name = "name";
    }
}

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"/>

Initializer.java

package com.demo.app.spring;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.*;

public class Initializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
        mvcContext.register(AppConfig.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(mvcContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }
}

AppConfig.java

package com.demo.app.spring;

import org.springframework.context.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.demo.app")
public class AppConfig {
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.x">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>app</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>${project.artifactId}</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.2.0.RELEASE</spring.version>
        <jetty.plugin.version>8.1.7.v20120910</jetty.plugin.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.12</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.plugin.version}</version>
                <configuration>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

File structure:

pom.xml
src
  |- main
      |- java
      |    |- com
      |        |- demo
      |             |- app
      |                 |- controller/DemoController.java
      |                 |- spring/AppConfig.java, Initializer.java
      |- webapp
           |- WEB-INF/web.xml

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to extract a JsonObject from a Java list?

I encountered an issue with two JsonObject objects that are within a list. When I create a new JsonObject and attempt to retrieve the list within it, I am getting a null value. Below is the code snippet: private int checkExisting(String productId, Li ...

Troubleshooting an issue in node.js when reading a utf8 encoded file on a Windows system

I am struggling to load a UTF8 json file from disk using node.js (0.10.29) on my Windows 8.1 machine. Below is the code snippet that I am trying to execute: var http = require('http'); var utils = require('util'); var path = require(&a ...

Unusual node encountered during JSON parsing

I am currently extracting data from this specific webpage: posts: [ { .... categories: [], tags: [], .... Within the 'post' object, there is a tag that provides information about the author: author: { id: 43, slug: "connergordon_2016", name: ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

Is there a way to develop a nested JSON web service using C#?

I am working on displaying a list of products with their product names and group ids using a webservice with different levels. For Level 0, the display should contain the group id with the product names as child levels. So far, I have created two diction ...

Converting JSON data into an array of JavaScript objects

Here is some of the JSON data I have: [ { "items": [ { "retailername": "Zop Now", "value": 475 }, { "retailername": "Snap Deal", "value": 265 ...

Loop through a section of parsed JSON data in Terraform in order to generate a Map

I am working on iterating over a block that is extracted from a JSON file to create a customizable Map block. The keys and values in the JSON files can vary between different files. The extraction process is carried out using a jsondecode() function. Her ...

AWS Automation Document: Leveraging aws:loop to iterate through the results of a previous task

Trying to understand how to use the aws:loop has been quite challenging, especially when it comes to using output from a previous step as input for the current step. In one of my steps (utilizing AWS-RunPowerSHellScript), I am producing an array (which I ...

Serialize the entity using JSON.NET JsonConvert will result in an empty array being returned

Currently, I am serializing my entity object using JsonConvert.SerializeObject. Here is an example of what I am doing: var test = JsonConvert.SerializeObject(MyEntityObject) The result of this test is : [ { "$id": "1", "Someproperty1": 1, ...

How can I transfer a MongoDB collection to an EJS file in the form of a sorted list?

I have successfully displayed the collection as a json object in its own route, but now I want to show the collection in a list under my index.ejs file (I'm still new to ejs and MongoDB). Below is the code that allows me to view the json object at lo ...

Fill out a dropdown menu by selecting options from another dropdown menu

I'm currently working on populating a dropdown list based on the selection of another dropdown list. Here's what I have so far: Below is the function that takes the selected value from the first dropdown list as a parameter: [AcceptVerbs(HttpVe ...

Using Python to generate a JSON file containing a list of artifacts through a loop

My file_list variable contains a list of files (artifacts), although it has been shortened for this example. print(type(file_list)) <class 'list'> print(file_list) ['file_AA.txt', 'file_BB.txt', 'file_CC.txt', ...

Utilize Java to Extract Nested JSON Data from Parquet File

I am currently working with Spark 1.5.2 and Java, trying to import a parquet file that has data originating from a JSON file. I am facing challenges in understanding how to extract a field that originally had nested JSON but is now represented as WrappedAr ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

Dashing List JSON Summary

In my current project, I'm setting up a Dashing job to retrieve data from an API using Ruby. SCHEDULER.every '15m', :first_in => 0 do |job| url = "https://blah.com" response = RestClient.get(url, {:Authorization => 'blahb ...

Ways to emphasize a particular <li> element?

Currently, I am delving into the world of React and facing a challenge. I have been trying to solve the issue below: When fetching some JSON data, it appears in this format: [ { "answerOptions": [ "Answer A", "Answer B", ...

I require the extraction of data from a MySQL database, converting it into a JSON array, and utilizing the array for auto-complete functionality in a text box

I have a task where I need to retrieve data from a MySQL database and transform it into a JSON array. I then want to use this JSON array for autocomplete functionality in textboxes. I know how to achieve this using separate PHP files to fetch the data from ...

Utilizing Selenium Builder tests in combination with Jenkins and GitHub

My objective: Establishing a streamlined test framework utilizing Selenium Builder as a Firefox plugin, GitHub, and Jenkins. Storing the test files in .json format is essential for my workflow. At this point, I prefer to stay away from Java and Maven. My ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...