Post on 16-Apr-2017
transcript
MULE: JSON TO OBJECT
HANDLING UNRECOGNIZED FIELD
JSON SUPPORT REFERENCE• JSON, short for JavaScript Object Notation, is a lightweight data
interchange format. • Mule supports binding JSON data to objects and marshalling Java
object to JSON using the Jackson Framework.• JSON transformers have been added in Studio to make it easy to
work with JSON encoded messages.
JSON BINDINGS (1/2)• Jackson uses annotations to describe how data is mapped to a Java
object model.• For example an JSON file that describes a person:
{ "id": 1, "name": "Max"}
JSON BINDINGS (2/2)• @JsonAutoDetect maps directly the field member names to JSON
field names.package com.mulesoft.learning;
import org.codehaus.jackson.annotate.JsonAutoDetect;
@JsonAutoDetectpublic class Person {
private String id; private String name; //getter-setter}
JSON TO OBJECT: DEMO - DESIGN• HTTP: an inbound endpoint for posting the JSON data.• JSON to Object: transforming the JSON data to a Java object.• Logger: displaying the log.
JSON TO OBJECT: DEMO - XML CONFIG• Two-way editing between graphical and XML views.
<flow name="jsonToObjectFlow"> <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/> <json:json-to-object-transformer returnClass="com.mulesoft.learning.Person" doc:name="JSON to Object"/> <logger message="#[payload]" level="INFO" doc:name="Logger"/></flow>
JSON TO OBJECT: TESTING (1/2)• Use a REST Client, e.g.: Postman, for posting the JSON data.
JSON TO OBJECT: TESTING (2/2)• Posting the JSON data with an unrecognized field: Failed!
JSON TO OBJECT: ISSUE• JSON to Object Transformer failed to transform an JSON data with
unrecognized field.• Root Exception stack trace:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "type" (Class com.mulesoft.learning.Person), not marked as ignorable.
• How to easily adapt to change if this issue happens?
JSON TO OBJECT: SOLUTION• Ignore unrecognized field.
package com.mulesoft.learning;
import org.codehaus.jackson.annotate.JsonAutoDetect;import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonAutoDetect@JsonIgnoreProperties(ignoreUnknown=true)public class Person {
private String id; private String name; //getter-setter}
JSON TO OBJECT: FINAL TESTING• Posting the JSON data with an unrecognized field: Success!
SUMMARY• JSON is natively supported in Mule.• JSON data can be bind automatically to Java object.• Unrecognized field can be handled by Jackson Framework.
RESOURCES• https://
docs.mulesoft.com/mule-user-guide/v/3.8/json-module-reference• https://
docs.mulesoft.com/mule-user-guide/v/3.8/native-support-for-json