简体   繁体   中英

How to get Java object field to be serialized and sent to the client

I have an AngularJS application using Ebean and Play Framework. I'm using Java 7. I have a Java object on the server that is supposed to be sent to the client after being fetched from the database. It is a RESTful service and objects are sent in Json. I added a new field to this object, it is itself an object. I expect this field to be serialized and sent to the client but it is not being sent. Is there any annotation or anything else I can do to get the field sent to the client? The field I want sent is call service, and it is a Resource object.

public Class DVMOrderItem extends OrderItem {
   private static final long serialVersionUID = -2757166118137807642L;
   @OneToOne(mappedBy = "discoOrderItem")
   protected Resource service;
   /** getters and setters available */

You should try to create a serializer for this field

First add an annotation above the field :

@JsonSerialize(using=MyJsonSerializer.class)

Then create your json serializer class :

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class MyJsonSerializer extends JsonSerializer<Customer>
{
    @Override
    public void             serialize(Customer comp, JsonGenerator gen, SerializerProvider provider)throws IOException, JsonProcessingException
    {
        //This is how to create a json object with jackson
        gen.writeStartObject();
        gen.writeObjectField("idCustomer", myValue1);
        gen.writeObjectField("name", myValue2);
        gen.writeEndObject();
    }
}

The MyJsonSerializer class will be call every time you want to serialize the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM