blob: b48f6672782aa519390deec5e1e33d199a034404 [file] [log] [blame]
/*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial impl
******************************************************************************/
package example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import model.Order;
/**
* Uses EclipseLink Moxy to convert an object to JSON.
* @author James Sutherland
*/
public class JSONSerializer implements Serializer {
JAXBContext context;
Marshaller marshaller;
Unmarshaller unmarshaller;
public JSONSerializer() {
try {
this.context = JAXBContext.newInstance(Order.class);
marshaller = this.context.createMarshaller();
marshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller = this.context.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
public byte[] serialize(Object object) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//StringWriter writer = new StringWriter();
marshaller.marshal(object, stream);
return stream.toByteArray();
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
public Object deserialize(byte[] bytes) {
try {
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
//StringReader reader = new StringReader(new String(bytes));
return unmarshaller.unmarshal(stream);
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
public String toString() {
return getClass().getSimpleName();
}
}