DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • NewRelic Logs With Logback on Azure Cloud
  • How To Extract a ZIP File and Remove Password Protection in Java

Trending

  • Beyond the Glass Slab: How AI Voice Assistants are Morphing Into Our Real-Life JARVIS
  • MCP Client Agent: Architecture and Implementation
  • Rust: The Must-Adopt Language for Modern Software Development
  • Parallel Data Conflict Resolution in Enterprise Workflows: Pessimistic vs. Optimistic Locking at Scale
  1. DZone
  2. Coding
  3. Languages
  4. EclipseLink MOXy and the Java API for JSON Processing - Object Model APIs

EclipseLink MOXy and the Java API for JSON Processing - Object Model APIs

By 
Blaise Doughan user avatar
Blaise Doughan
·
Aug. 07, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
13.5K Views

Join the DZone community and get the full member experience.

Join For Free

The Java API for JSON Processing (JSR-353) is the Java standard for producing and consuming JSON which was introduced as part of Java EE 7.  JSR-353 includes object (DOM like) and stream (StAX like) APIs.  In this post I will demonstrate the initial JSR-353 support we have added to MOXy's JSON binding in EclipseLink 2.6.  You can now use MOXy to marshal to:

  • javax.json.JsonArrayBuilder
  • javax.json.JsonObjectBuilder
 And unmarshal from:
  • javax.json.JsonStructure
  • javax.json.JsonObject
  • javax.json.JsonArray

You can try this out today using a nightly build of EclipseLink 2.6.0:
  • http://www.eclipse.org/eclipselink/downloads/nightly.php

The JSR-353 reference implementation is available here:
  • https://java.net/projects/jsonp/downloads/download/ri/javax.json-ri-1.0.zip

Java Model
Below is the simple customer model that we will use for this post.  Note for this example we are only using the standard JAXB (JSR-222) annotations.

Customer

package blog.jsonp.moxy;
 
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlType(propOrder={"id", "firstName", "lastName", "phoneNumbers"})
public class Customer {
 
    private int id;
    private String firstName;
    private String lastName;
    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    @XmlElement(nillable=true)
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    @XmlElement
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }
 
}
PhoneNumber

package blog.jsonp.moxy;
 
import javax.xml.bind.annotation.*;
 
@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {
 
    private String type;
 
    private String number;
 
    public String getType() {
        return type;
    }
 
    public void setType(String type) {
        this.type = type;
    }
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
 
}

jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see:  Specifying EclipseLink MOXy as your JAXB Provider)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Marshal Demo
In the demo code below we will use a combination of JSR-353 and MOXy APIs to produce JSON.  JSR-353's JsonObjectBuilder and JsonArrayBuilder are used to produces instances of JsonObject and JsonArray.  We can use MOXy to marshal to these builders by wrapping them in instances of MOXy's JsonObjectBuilderResult and JsonArrayBuilderResult.

package blog.jsonp.moxy;
 
import java.util.*;
import javax.json.*;
import javax.json.stream.JsonGenerator;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.oxm.json.*;
 
public class MarshalDemo {
 
    public static void main(String[] args) throws Exception {
        // Create the EclipseLink JAXB (MOXy) Marshaller
        Map<String, Object> jaxbProperties = new HashMap<String, Object>(2);
        jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class},
            jaxbProperties);
        Marshaller marshaller = jc.createMarshaller();
 
        // Create the JsonArrayBuilder
        JsonArrayBuilder customersArrayBuilder = Json.createArrayBuilder();
         
        // Build the First Customer
        Customer customer = new Customer();
        customer.setId(1);
        customer.setFirstName("Jane");
        customer.setLastName(null);
         
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.setType("cell");
        phoneNumber.setNumber("555-1111");
        customer.getPhoneNumbers().add(phoneNumber);
         
        // Marshal the First Customer Object into the JsonArray
        JsonArrayBuilderResult result =
            new JsonArrayBuilderResult(customersArrayBuilder);
        marshaller.marshal(customer, result);
 
        // Build List of PhoneNumer Objects for Second Customer
        List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(2);
         
        PhoneNumber workPhone = new PhoneNumber();
        workPhone.setType("work");
        workPhone.setNumber("555-2222");
        phoneNumbers.add(workPhone);
 
        PhoneNumber homePhone = new PhoneNumber();
        homePhone.setType("home");
        homePhone.setNumber("555-3333");
        phoneNumbers.add(homePhone);
         
        // Marshal the List of PhoneNumber Objects
        JsonArrayBuilderResult arrayBuilderResult = new JsonArrayBuilderResult();
        marshaller.marshal(phoneNumbers, arrayBuilderResult);
 
        customersArrayBuilder
            // Use JSR-353 APIs for Second Customer's Data
            .add(Json.createObjectBuilder()
                .add("id", 2)
                .add("firstName", "Bob")
                .addNull("lastName")
                // Included Marshalled PhoneNumber Objects
                .add("phoneNumbers", arrayBuilderResult.getJsonArrayBuilder())
             )
        .build();
         
        // Write JSON to System.out
        Map<String, Object> jsonProperties = new HashMap<String, Object>(1);
        jsonProperties.put(JsonGenerator.PRETTY_PRINTING, true);
        JsonWriterFactory writerFactory = Json.createWriterFactory(jsonProperties);
        JsonWriter writer = writerFactory.createWriter(System.out);
        writer.writeArray(customersArrayBuilder.build());
        writer.close();
    }
 
}
Highlighted lines: 36, 37, 38, 54, 55, 64


Output
Below is the output from running the marshal demo (MarshalDemo).  The highlighted portions (lines 2-12 and 18-25) correspond to the portions that were populated from our Java model.

[
    {
        "id":1,
        "firstName":"Jane",
        "lastName":null,
        "phoneNumbers":[
            {
                "type":"cell",
                "number":"555-1111"
            }
        ]
    },
    {
        "id":2,
        "firstName":"Bob",
        "lastName":null,
        "phoneNumbers":[
            {
                "type":"work",
                "number":"555-2222"
            },
            {
                "type":"home",
                "number":"555-3333"
            }
        ]
    }
]
Highlighted lines: 2-12, 18-25

Unmarshal Demo
MOXy enables you to unmarshal from a JSR-353 JsonStructure (JsonObject or JsonArray).  To do this simply wrap the JsonStructure in an instance of MOXy's JsonStructureSource and use one of the unmarshal operations that takes an instance of Source.

package blog.jsonp.moxy;
 
import java.io.FileInputStream;
import java.util.*;
import javax.json.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.oxm.json.JsonStructureSource;
 
public class UnmarshalDemo {
 
    public static void main(String[] args) throws Exception {
        try (FileInputStream is = new FileInputStream("src/blog/jsonp/moxy/input.json")) {
            // Create the EclipseLink JAXB (MOXy) Unmarshaller
            Map<String, Object> jaxbProperties = new HashMap<String, Object>(2);
            jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
            jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
            JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class},
                jaxbProperties);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
 
            // Parse the JSON
            JsonReader jsonReader = Json.createReader(is);
 
            // Unmarshal Root Level JsonArray
            JsonArray customersArray = jsonReader.readArray();
            JsonStructureSource arraySource = new JsonStructureSource(customersArray);
            List<Customer> customers =
                (List<Customer>) unmarshaller.unmarshal(arraySource, Customer.class)
                .getValue();
            for(Customer customer : customers) {
                System.out.println(customer.getFirstName());
            }
 
            // Unmarshal Nested JsonObject
            JsonObject customerObject = customersArray.getJsonObject(1);
            JsonStructureSource objectSource = new JsonStructureSource(customerObject);
            Customer customer = unmarshaller.unmarshal(objectSource, Customer.class)
                .getValue();
            for(PhoneNumber phoneNumber : customer.getPhoneNumbers()) {
                System.out.println(phoneNumber.getNumber());
            }
        }
    }
 
}
Highlighted lines: 27-30, 37-39


Input (input.json)
The following JSON input will be converted to a JsonArray using a JsonReader.

[
    {
        "id":1,
        "firstName":"Jane",
        "lastName":null,
        "phoneNumbers":[
            {
                "type":"cell",
                "number":"555-1111"
            }
        ]
    },
    {
        "id":2,
        "firstName":"Bob",
        "lastName":null,
        "phoneNumbers":[
            {
                "type":"work",
                "number":"555-2222"
            },
            {
                "type":"home",
                "number":"555-3333"
            }
        ]
    }
]
Highlighted lines: 4, 15, 20, 24

Output
Below is the output from running the unmarshal demo (UnmarshalDemo).
Jane
Bob
555-2222
555-3333

JSON API Java (programming language) EclipseLink Object model Processing Object (computer science)

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • NewRelic Logs With Logback on Azure Cloud
  • How To Extract a ZIP File and Remove Password Protection in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: