JSON Articles

Page 11 of 16

JSON Schema Support using Jackson in Java?

raja
raja
Updated on 08-Jul-2020 6K+ 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

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

raja
raja
Updated on 08-Jul-2020 7K+ 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
raja
Updated on 08-Jul-2020 19K+ 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
raja
Updated on 08-Jul-2020 3K+ 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
raja
Updated on 07-Jul-2020 3K+ 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 merge two JSON strings in an order using JsonParserSequence in Java?

raja
raja
Updated on 07-Jul-2020 921 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 map the JSON data with Jackson Object Model in Java?

raja
raja
Updated on 07-Jul-2020 3K+ 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 implement custom FieldNamingStrategy using Gson in Java?

raja
raja
Updated on 07-Jul-2020 1K+ 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 JsonFactory settings using Jackson in Java?

raja
raja
Updated on 07-Jul-2020 1K+ Views

The JsonFactory class is a thread-safe and responsible for creating instances of writer and reader. The list of settings that can be turned on/off is present in an enumeration JsonFactory.Feature, it contains static method values() that return the enum constant of this type with the specified name.Syntaxpublic static enum JsonFactory.Feature extends EnumExampleimport com.fasterxml.jackson.core.JsonFactory; public class JsonFactorySettingsTest {    public static void main(String[] args) {       JsonFactory jsonFactory = new JsonFactory();       for(JsonFactory.Feature feature : JsonFactory.Feature.values()) {          boolean result = jsonFactory.isEnabled(feature);          System.out.println(feature.name() + ":" + result);       }    } }OutputINTERN_FIELD_NAMES:true ...

Read More

FieldNamingPolicy enum using Gson in Java?

raja
raja
Updated on 07-Jul-2020 1K+ Views

Gson library provides the naming conventions as part of enum FieldNamingPolicy. We can set the field naming policy using the setFieldNamingPolicy() method of the GsonBuilder class.FieldNamingPolicy enum ConstantsIDENTITY − Using this naming policy, the field name is unchanged.LOWER_CASE_WITH_DASHES − Using this naming policy, modify the Java Field name from its camel-cased form to a lower case field name where each word is separated by a dash (-).LOWER_CASE_WITH_UNDERSCORES − Using this naming policy, modify the Java Field name from its camel-cased form to a lower case field name where each word is separated by an underscore (_).UPPER_CAMEL_CASE − Using this naming policy, ...

Read More
Showing 101–110 of 152 articles
« Prev 1 9 10 11 12 13 16 Next »
Advertisements