Found 2620 Articles for Java

JSON Schema Support using Jackson in Java?

raja
Updated on 08-Jul-2020 06:46:35

4K+ Views

JSON Schema is a specification for JSON based format for defining the structure of JSON data. The JsonSchema class can provide a contract for what JSON data is required for a given application and how to interact with it. The JsonSchema can define validation, documentation, hyperlink navigation, and interaction control of JSON data. We can generate the JSON schema using the generateSchema() method of JsonSchemaGenerator, this class wraps the JSON schema generation functionality.Syntaxpublic JsonSchema generateSchema(Class type) throws com.fasterxml.jackson.databind.JsonMappingExceptionExampleimport com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator; import java.util.List; public class JSONSchemaTest {    public static void main(String[] args) throws JsonProcessingException {     ... Read More

Differences between org.simple.json and org.json libraries in Java?

raja
Updated on 08-Jul-2020 06:19:28

2K+ Views

The org.json.simple library allows us to read and write JSON data in Java. In other words, we can encode and decode the JSON object. The org.json.simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple.jar file to execute a JSON program whereas org.json library has classes to parse JSON for Java. It also converts between JSON and XML, HTTP header, Cookies,  and CDF. The org.json package contains important classes like JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie and CookieList. We need to install the json.jar file to execute a JSON program.Example for org.simple.json packageimport org.json.simple.JSONObject; public class SimpleJsonTest {   ... Read More

How to convert Java array or ArrayList to JsonArray using Gson in Java?

raja
Updated on 08-Jul-2020 06:20:07

6K+ Views

The Java Arrays are objects which store multiple variables of the same type, it holds primitive types and object references and an ArrayList can represent a resizable list of objects. We can add, remove, find, sort and replace elements using the list. A JsonArray can parse text from a string to produce a vector-like object. We can convert an array or ArrayList to JsonArray using the toJsonTree().getAsJsonArray() method of Gson class.Syntaxpublic JsonElement toJsonTree(java.lang.Object src)Exampleimport com.google.gson.*; import java.util.*; public class JavaArrayToJsonArrayTest {    public static void main(String args[]) {       String[][] strArray = {{"elem1-1", "elem1-2"}, {"elem2-1", "elem2-2"}};       ArrayList arrayList = ... Read More

How to resolve "Expected BEGIN_OBJECT but was BEGIN_ARRAY" using Gson in Java?

raja
Updated on 08-Jul-2020 05:49:52

14K+ Views

While deserializing, a Gson can expect a JSON object but it can find a JSON array. Since it can't convert from one to the other, it can throw an error as "JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY" at the runtime.Exampleimport com.google.gson.Gson; public class GsonErrorTest {    public static void main(String args[]) throws Exception {       String json = "{\"employee\":[{\"name\":\"Raja Ramesh\", \"technology\":\"java\"}]}";       Gson gson = new Gson();       Software software = gson.fromJson(json, Software.class);       System.out.println(software);    } } class Software {    Employee employee; } class Employee {    String name; ... Read More

How to serialize a JSON object with JsonWriter using Object Model in Java?

raja
Updated on 08-Jul-2020 05:40:56

2K+ Views

The javax.json.JsonWriter interface can write a JSON object or array structure to an output source. The class javax.json.JsonWriterFactory contains methods to create JsonWriter instances. A factory instance can be used to create multiple writer instances with the same configuration. We can create writers from output source using the static method createWriter() of javax.json.Json class.Syntaxpublic static JsonWriter createWriter(Writer writer)In the below example, we can serialize a JSON object using the JsonWriter interface.Exampleimport java.io.StringWriter; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; public class JsonWriterTest {    public static void main(String[] args) {       JsonObject jsonObj = Json.createObjectBuilder()                  .add("name", ... Read More

How to handle the errors generated while deserializing a JSON in Java?

raja
Updated on 07-Jul-2020 13:18:11

2K+ Views

The DeserializationProblemHandler class can be registered to get called when a potentially recoverable problem is encountered during the deserialization process. We can handle the errors generated while deserializing the JSON by implementing the handleUnknownProperty() method of DeserializationProblemHandler class.Syntaxpublic boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer deserializer, Object beanOrClass, String propertyName) throws IOExceptionExampleimport java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.*; public class DeserializationErrorTest {    public static void main(String[] args) throws JsonMappingException, JsonGenerationException, IOException {       String jsonString = "{\"id\":\"101\", \"name\":\"Ravi Chandra\", \"address\":\"Pune\", \"salary\":\"40000\" }";       ObjectMapper objectMapper = new ObjectMapper();       DeserializationProblemHandler deserializationProblemHandler = new UnMarshallingErrorHandler();     ... Read More

How to map the JSON data with Jackson Object Model in Java?

raja
Updated on 07-Jul-2020 13:04:14

2K+ Views

The ObjectMapper class provides functionality for converting between Java objects and matching JSON constructs. We can achieve mapping of JSON data represented by an Object Model to a particular Java object using a tree-like data structure that reads and stores the entire JSON content in memory. In the first step, read the JSON data into the JsonNode object then mapped it to another instance by calling the treeToValue() method of ObjectMapper class.Syntaxpublic T treeToValue(TreeNode n, Class valueType) throws JsonProcessingExceptionExampleimport java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; public class JsonTreeModelDemo {    public static void main(String[] args) throws JsonProcessingException, IOException {       String jsonString ... Read More

How to merge two JSON strings in an order using JsonParserSequence in Java?

raja
Updated on 07-Jul-2020 13:06:13

609 Views

The JsonParserSequence is a helper class that can be used to create a parser containing two sub-parsers placed in a particular sequence. We can create a sequence using the static method createFlattened() of the JsonParserSequence class.Syntaxpublic static JsonParserSequence createFlattened(JsonParser first, JsonParser second)Exampleimport java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.*; public class JsonParserSequenceTest {    public static void main(String[] args) throws JsonParseException, IOException {       String jsonString1 = "{\"id\":\"101\", \"name\":\"Ravi Chandra\", \"address\":\"Pune\"}";       String jsonString2 = "{\"id\":\"102\", \"name\":\"Raja Ramesh\", \"address\":\"Hyderabad\", \"contacts\":[{\"mobile\":\"9959984805\", \"home\":\"7702144400\"}]}";       JsonFactory jsonFactory = new JsonFactory();       JsonParser jsonParser1 = jsonFactory.createParser(jsonString1);       JsonParser jsonParser2 = jsonFactory.createParser(jsonString2);       ... Read More

How to implement custom FieldNamingStrategy using Gson in Java?

raja
Updated on 07-Jul-2020 12:39:14

716 Views

The FieldNamingStrategy is a mechanism for providing custom field naming in Gson. This allows the client code to translate field names into a particular convention that is not supported as a normal Java field declaration rules. The translateName() method will prefix every field name with the string “pre_”.In the below example, we can implement the Custom FieldNamingStrategy.Exampleimport java.lang.reflect.Field; import com.google.gson.*; public class GsonFieldNamingStrategyTest {    public static void main(String[] args) {       Employee emp = new Employee();       emp.setEmpId(115);       emp.setFirstName("Adithya");       emp.setLastName("Jai");       CustomFieldNamingStrategy customFieldNamingStrategy = new CustomFieldNamingStrategy();     ... Read More

How to get the JSONParser default settings using Jackson in Java?

raja
Updated on 07-Jul-2020 12:18:20

267 Views

All the default settings of JSON Parser can be represented using the JsonParser.Feature enumeration. The JsonParser.Feature.values() will return all the features that are available for JSONParser but whether a feature is enabled or disabled for a particular parser can be determined using the isEnabled() method of JsonParser. Syntaxpublic static enum JsonParser.Feature extends EnumExampleimport com.fasterxml.jackson.core.*; import java.io.*; public class JsonParserSettingsTest {    public static void main(String[] args) throws IOException {       String json = "[{\"name\":\"Adithya\", \"age\":\"30\"}, " + "{\"name\":\"Ravi\", \"age\":\"35\"}]";       JsonFactory jsonFactory = new JsonFactory();       JsonParser jsonParser = jsonFactory.createParser(json);       for(JsonParser.Feature feature : JsonParser.Feature.values()) {       ... Read More

Advertisements