Thursday, July 16, 2015

Serialize manually using faster jackson library in spring

I am trying to get a JSON Structure for my object Order which internally has OrderDetails as oneToMany mapping,

@Entity
public class Order {    
    /*
        All the fields associated with this class
    */      
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "orderId")
    private Set<OrderDetails> orderDetails;

    //Getters for all properties defined in this class as jackson would depend on this thing
}
In my case I am using a textWebSocket which is expecting a message only in String format so I need to serialize the objects and push to the client, I am depending on faster jackson to do it and here it goes,

public String getObjectAsString()
{

    //orderObjs : Considering this is the list of objects of class Order

    ObjectMapper objMapper = new ObjectMapper();
            returnValue = objMapper.writerWithType(
                    objMapper.getTypeFactory().constructCollectionType(
                            List.class, Order.class)).writeValueAsString(
                    orderObjs);
    return returnValue;
}

objMapper.writerWithType(objMapper.getTypeFactory().constructCollectionType(List.class,Order.class)).writeValueAsString(orderObjs);

No comments:

Post a Comment