derlin
11/16/2016 - 11:49 AM

Unmarshal json string and json file using java EclipseLink / MOXy provider (glassfish 4.0.1 and JUnit4)

Unmarshal json string and json file using java EclipseLink / MOXy provider (glassfish 4.0.1 and JUnit4)

<?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.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ch.derlin</groupId>
    <artifactId>unmarshal-test</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
  
    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jersey.version>2.23</jersey.version>
        <eclipselink.version>2.5.2</eclipselink.version>
    </properties>
    
    <dependencies>
        <!-- eclipselink -->
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>${eclipselink.version}</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${eclipselink.version}</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- jersey -->        
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-bean-validation</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.bundles.repackaged</groupId>
            <artifactId>jersey-guava</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>       
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
// this file is located in src/test/resources
[
    {
        "objectId": 1,
        "value": 72.50916877421835,
        "comment": "",
        "token": "aaaaaa34aaagaaasaaaaaaaaaaaaaaaa",
        "timestamp": "2016-08-14T18:54:22"
    },
    {
        "objectId": 1,
        "value": "72",
        "comment": "hello",
        "token": "aaaaaaaaaaaasaafaaafaaaxaa45aaaa",
        "timestamp": "20164-08-14T18:54:22"
    }
]
import java.util.Date;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 * @author lucy
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Measure {
    

    @NotNull
    @Min( value = 0, message = "objectId must be positive." )
    private Integer objectId;

    @NotNull
    @Size( min = 32, max = 32, message = "wrong size: should be 32 chars long." )
    private String token;

    @NotNull
    private String timestamp;

    @NotNull
    private String value;

    @Size( max = 1024, message = "too long. Maximum set to 1024." )
    private String comment;

    
    private Integer owner;
    
    public Measure(){}

    public Integer getObjectId() {
        return objectId;
    }

    public void setObjectId(Integer objectId) {
        this.objectId = objectId;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getTimestamp() {
        return timestamp;
    }

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

    
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Integer getOwner() {
        return owner;
    }

    public void setOwner(Integer owner) {
        this.owner = owner;
    }   
}
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.json.simple.JSONArray;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


/**
 *
 * @author lucy linder
 */
public class UnmarshalTest {

    Unmarshaller unmarshaller;

    public UnmarshalTest() {
    }

    @Before
    public void setUp() throws JAXBException {
        System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
        Map<String, Object> jaxbProperties = new HashMap<>(2);
        jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[]{Measure.class}, jaxbProperties);
        unmarshaller = jc.createUnmarshaller();
    }

    private Measure unmarshalString(String json) {
        try {
            return unmarshaller.unmarshal(
                    new StreamSource(new StringReader(json)),
                    Measure.class).getValue();
        } catch (JAXBException e) {
            return null;
        }

    }
    
    private JAXBElement<Measure> unmarshalFile(String filepath) {
        try {
            InputStream stream = getClass().getResourceAsStream(filepath);
            StreamSource json = new StreamSource(stream);
            // Parse the JSON
            return unmarshaller.unmarshal(json, Measure.class);
            
        } catch (Exception ex) {
            return null;
        }
    }


    @Test
    public void test1() throws JAXBException {
               
        List<Measure> coll = (List<Measure>) unmarshalFile("/inputs.json").getValue();
        Assert.assertNotNull(coll);
    }
    
    @Test
    public void test2() throws JAXBException {

        String json = "'{\"objectId\":1,\"value\":72.50916877421835,\"comment\":\"\",\"token\":\"aaeeaaaa34aaaaaaaaaaaavaaaaaaaaa\", "
                + "\"timestamp\":\"2016-08-14T18:54:22\"}'";

        Measure measure = (Measure) unmarshalString(json);
        Assert.assertNotNull(measure);
        
        json = "'{\"objectId\":15,\"value\":72.50916877421835,\"comment\":\"\",\"token\":\"baaaaaaaaaaaaaaaaaaaaaaaaaaaaa12\", "
                + "\"timestamp\":\"2017-12-14T18:54:22\"}'";
        measure = (Measure) unmarshalString(json);
        Assert.assertNotNull(measure);
    }

}