EzDevInfo.com

jackson interview questions

Top jackson frequently asked interview questions

Jackson Vs. Gson [closed]

After searching through some existing libraries for JSON, I have finally ended up with these two:

  • Jackson
  • Google GSon

I am a bit partial towards GSON, but word on the net is that GSon suffers from a certain celestial performance issue (as of Sept 2009).

I am continuing my comparison; in the meantime, I'm looking for help to make up my mind.


Source: (StackOverflow)

How to deserialize JS date using Jackson?

I'm getting a date string from ExtJS in the format:

"2011-04-08T09:00:00"

when i try to deserialize this date, it changes the timezone to Indian Standard Time (adds +5:30 to the time) . This is how i'm deserializing the date:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);

Doing this also doesn't change the timezone. I still get the date in IST:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);

How do I deserialize the date in the way in which it is coming without the hassles of Timezone?


Source: (StackOverflow)

Advertisements

Convert Java Object to JsonNode in Jackson [duplicate]

This question already has an answer here:

Is it possible to directly convert a Java Object to an JsonNode-Object?

The only way I found to solve this is to convert the Java Object to String and then to JsonNode:

ObjectMapper mapper = new ObjectMapper(); 
String json = mapper.writeValueAsString(object);
JsonNode jsonNode = mapper.readTree(json);

Source: (StackOverflow)

Jackson enum Serializing and DeSerializer

I'm using JAVA 1.6 and Jackson 1.9.9 I've got an enum

public enum Event {
    FORGOT_PASSWORD("forgot password");

    private final String value;

    private Event(final String description) {
        this.value = description;
    }

    @JsonValue
    final String value() {
        return this.value;
    }
}

I've added a @JsonValue, this seems to do the job it serializes the object into:

{"event":"forgot password"}

but when I try to deserialize I get a

Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.globalrelay.gas.appsjson.authportal.Event from String value 'forgot password': value not one of declared Enum instance names

What am I missing here?


Source: (StackOverflow)

How do I use a custom Serializer with Jackson?

I have two Java classes that I want to serialize to JSON using Jackson:

public class User {
    public final int id;
    public final String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class Item {
    public final int id;
    public final String itemNr;
    public final User createdBy;

    public Item(int id, String itemNr, User createdBy) {
        this.id = id;
        this.itemNr = itemNr;
        this.createdBy = createdBy;
    }
}

I want to serialize an Item to this JSON:

{"id":7, "itemNr":"TEST", "createdBy":3}

with User serialized to only include the id. I will also be able to serilize all user objects to JSON like:

{"id":3, "name": "Jonas", "email": "jonas@example.com"}

So I guess that I need to write a custom serializer for Item and tried with this:

public class ItemSerializer extends JsonSerializer<Item> {

@Override
public void serialize(Item value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,
        JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeNumberField("id", value.id);
    jgen.writeNumberField("itemNr", value.itemNr);
    jgen.writeNumberField("createdBy", value.user.id);
    jgen.writeEndObject();
}

}

I serialize the JSON with this code from Jackson How-to: Custom Serializers:

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                              new Version(1,0,0,null));
simpleModule.addSerializer(new ItemSerializer());
mapper.registerModule(simpleModule);
StringWriter writer = new StringWriter();
try {
    mapper.writeValue(writer, myItem);
} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

But I get this error:

Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() (use alternative registration method?)
    at org.codehaus.jackson.map.module.SimpleSerializers.addSerializer(SimpleSerializers.java:62)
    at org.codehaus.jackson.map.module.SimpleModule.addSerializer(SimpleModule.java:54)
    at com.example.JsonTest.main(JsonTest.java:54)

How can I use a custom Serializer with Jackson?


This is how I would do it with Gson:

public class UserAdapter implements JsonSerializer<User> {

    @Override 
    public JsonElement serialize(User src, java.lang.reflect.Type typeOfSrc,
            JsonSerializationContext context) {
        return new JsonPrimitive(src.id);
    }
}

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(User.class, new UserAdapter());
    Gson gson = builder.create();
    String json = gson.toJson(myItem);
    System.out.println("JSON: "+json);

But I need to do it with Jackson now, since Gson doesn't have support for interfaces.


Source: (StackOverflow)

Converting Java objects to JSON with Jackson

I want my JSON to look like this:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

Code so far:

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {
        return information;
    }

    public void setInformation(List<ValueItems> information) {
        this.information = information;
    }

    @Override
    public String toString() {
        return String.format("{information:%s}", information);
    }

}

and

public class ValueItems {

    private String timestamp;
    private String feature;
    private int ean;
    private String data;


    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){
        this.timestamp = timestamp;
        this.feature = feature;
        this.ean = ean;
        this.data = data;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getFeature() {
        return feature;
    }

    public void setFeature(String feature) {
        this.feature = feature;
    }

    public int getEan() {
        return ean;
    }

    public void setEan(int ean) {
        this.ean = ean;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
    }
}

I just missing the part how I can convert the Java object to JSON with Jackson:

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?


Source: (StackOverflow)

Representing null in JSON

What is the preferred method for returning null values in JSON? Is there a different preference for primitives?

For example, if my object on the server has an Integer called "myCount" with no value, the most correct JSON for that value would be:

{}

or

{
    "myCount": null
}

or

{
    "myCount": 0
}

Same question for Strings - if I have a null string "myString" on the server, is the best JSON:

{}

or

{
    "myString": null
}

or

{
    "myStrung": ""
}

or (lord help me)

{
    "myString": "null"
}

I like the convention for collections to be represented in the JSON as an empty collection http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

An empty Array would be represented:

{
    "myArray": []
}

EDIT Summary

The 'personal preference' argument seems realistic, but short sited in that, as a community will be consuming greater numbers of disparate services/sources. Conventions for JSON structure would help normalize consumption and reuse of said services. As far as establishing a standard, I would suggest adopting most of the Jackson conventions with a few exceptions:

  • Objects are preferred over primitives.
  • Empty collections are preferred over null.
  • Objects with no value are represented as null.
  • Primitives return their value.

If you are returning a JSON object with mostly null values, you may have a candidate for refactoring into multiple services.

{

    "value1": null,

    "value2": null,

    "text1": null,

    "text2": "hello",

    "intValue": 0, //use primitive only if you are absolutely sure the answer is 0

    "myList": [],

    "myEmptyList": null, //NOT BEST PRACTICE - return [] instead

    "boolean1": null, //use primitive only if you are absolutely sure the answer is true/false

    "littleboolean": false

}

The above JSON was generated from the following Java class.

package jackson;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonApp {

    public static class Data {

        public Integer value1;

        public Integer value2;

        public String text1;

        public String text2 = "hello";

        public int intValue;

        public List<Object> myList = new ArrayList<Object>();

        public List<Object> myEmptyList;

        public Boolean boolean1;

        public boolean littleboolean;

    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(new Data()));
    }
}

Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
</dependency>

Source: (StackOverflow)

How to convert a JSON string to a Map with Jackson JSON

This is my first time trying to do something useful with Java.. I'm trying to do something like this but it doesn't work:

Map<String, String> propertyMap = new HashMap<String, String>();

propertyMap = JacksonUtils.fromJSON(properties, Map.class);

But the IDE says: 'Unchecked assignment Map to Map<String,String>'

What's the right way to do this? I'm only using Jackson because that's what is already available in the project, is there a native Java way of converting to/from JSON?

In PHP I would simply json_decode($str) and I'd get back an array. I need basically the same thing here.

Thanks!


Source: (StackOverflow)

Serializing enums with Jackson

I have an Enum desrcibed below:

public enum OrderType {

  UNKNOWN(0, "Undefined"),
  TYPEA(1, "Type A"),
  TYPEB(2, "Type B"),
  TYPEC(3, "Type C");

  private Integer id;
  private String name;

  private WorkOrderType(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  //Setters, getters....
}

I return enum array with my controller ( new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};), and Spring serializes it into the following json string:

["UNKNOWN", "TYPEA", "TYPEB", "TYPEC"] 

What is the best approach to force Jackson to serialize enums just like POJOs? E.g.:

[
  {"id": 1, "name": "Undefined"},
  {"id": 2, "name": "Type A"},
  {"id": 3, "name": "Type B"},
  {"id": 4, "name": "Type C"}
]

I played with different annotations but couldn't manage to get such result.


Source: (StackOverflow)

Only using @JsonIgnore during serialization, but not deserialization

I have a user object that is sent to and from the server. When I send out the user object I don't want to send the hashed password to the client. So I added @JsonIgnore on the password property, but this also blocks it from being deserialized into the password which makes it hard to sign up users when they ain't got a password.

How can I only get @JsonIgnore to apply to serialization and not deserialization? I'm using Spring JSONView so I don't have a ton of control over the ObjectMapper.

Things I've tried:

  1. Add @JsonIgnore to the property
  2. Add @JsonIgnore on the getter method only

Source: (StackOverflow)

downloading jackson.codehaus.org jar

I need to download a json parser so I go to the jackson.codehaus.org website. Instead of a convenient link to click and download the jar/jars, they have me going in circles. Does anyone know where the jars are -- exactly?


Source: (StackOverflow)

Jackson: how to prevent field serialization

I have an entity class with a password field:

class User {
    private String password;

    //setter, getter..
}

I want this field to be skipped during serialization. But it should still be able to DEserialize. This is needed, so that the client can send me a new password, but is not able to read the current one.

How do I accomplish this with Jackson?


Source: (StackOverflow)

how to specify jackson to only use fields - preferably globally

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

I would like to use the fields as the canonical source of serialization config and thus don't want jackson to look at properties at all.

I can do this on an individual class basis with the annotation:

 @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)

But I don't want to have to put this on every single class...

Is it possible to configure this globally? Like add some to the Object Mapper?


Source: (StackOverflow)

How to serialize Joda DateTime with Jackson JSON processer?

How do I get Jackson to serialize my Joda DateTime object according to a simple pattern (like "dd-MM-yyyy"?

I've tried:

@JsonSerialize(using=DateTimeSerializer.class)
private final DateTime date;

I've tried:

ObjectMapper mapper = new ObjectMapper()
    .getSerializationConfig()
    .setDateFormat(df);

Thanks!


Source: (StackOverflow)

Serializing with Jackson (JSON) - getting "No serializer found"?

I get the an exception when trying to serialize a very simple object using Jackson. The error:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class MyPackage.TestA and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )

Below is the simple class and code to serialize.

Can anyone tell my why I get this error?

public class TestA {
    String SomeString = "asd";
}

TestA testA = new TestA();
ObjectMapper om = new ObjectMapper();
try {
    String testAString = om.writeValueAsString(testA); // error here!

    TestA newTestA = om.readValue(testAString, TestA.class);
} catch (JsonGenerationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (JsonMappingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Source: (StackOverflow)