How to Convert a Java Object into a JSON String

How to Convert a Java Object into a JSON String

In this article, you'll learn how to convert a Java Object into a JSON String

When learning how to write Java-based software, one of the first snags developers hit is how to connect their code with other software. This is usually where JSON comes in. While you might be a wizard with Java, JSON is another animal.

What is a Java Object? 

A Java object is a combination of data and procedures that work on the available data.

Objects have both states and behaviors. In Java, an object is created using the keyword “new”.

Objects are created from templates known as classes. 

An object is an instance of a class.

For example, our “Cat object” has:States – color, name, breed

the state of an object is stored in fields (variables). Behavior – purring, eating, sleeping methods (functions) display the object’s behavior.

What is a JSON String?
  • JSON is an acronym for JavaScript Object Notation
  • JSON was designed as a data interchange format and has a syntax that is a subset of JavaScript.
  • Context which is surrounded by quotes (single or double), loaded from a text file etc. are called JSON strings.
  • e.g.
  • {“id”:1,”name”:”SiAm”,”color”:”Cream”,”eyecolor”:”Blue”,”breed”:”Siamese”}
  • JSON is interoperable meaning that it’s language/platform independent.     
  • JSON format is used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and mobile/web application, serving as an alternative to XML. 
Common Uses for Converting Java Obj. to JSON String

The example below demonstrates a client server scenario where the RESTful Web Service accepts data in XML/JSON

  • The RESTful web server app is designed using java: 
  • enduser doesn’t understand the xml/json but that’s not an issue
  • the enduser communicates with a mobile app which might be android
  • the enduser communicates with a mobile app which might be php
  • the mobile/web app communicates with the RESTful web service via XML/JSON

When would you want to convert from Java Obj to JSON string?

In our example diagram above, our RESTful web service was designed using Java. 

Since Java objects are only understood by Java applications we need to convert the java object to JSON when creating a web service for the android app. Let’s say the mobile app is a hybrid app where the front end is handled by android view and the data transactions are sent through its own web services using JSON. In this instance we need to send/receive requests from the android app to/from our database using web services/api using JSON data structure.

  • JSON is a simple string format data. JSON is readable format. It is very easy to read and infer information from it.
  • JSON format is simple to use.
  • JSON is quite light-weight compared to other formats like XML etc,.
  • JSON format can be easily converted into Java objects in an Object oriented manner.
  • JSON is interoperable: program and platform independent.
Java Object to Json String: Tutorial

Step by step examples of how to convert Java Object to JSON string

The most common way to convert Java Object to JSON string is to use an API. The most common APIs for this purpose are Jackson and GSON.

JACKSON API example

This example shows how to use JACKSON API to convert a Java Object into a JSON String.

We can use the ObjectMapper class provided by the Jackson API for our conversion.

  • writeValueAsString() is used to convert java obj to JSON
  • readValue() is used to convert JSON into java obj

Step 1: Include the JACKSON JAR files into your classpath.

When using MAVEN for dependency management (recommended) you can include the following dependency to download JAR files, any dependency for JACKSON and automatically include it in your project’s classpath.

Add the following dependency to the pom file:

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>

Step 2: Use the Jackson API ObjectMapper class to convert Java Object to a JSON string

ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(cat);
System.out.println("ResultingJSONstring = " + json);
//System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
This example uses the following code: class useJACKSONapiToConvertJavaOBJtoJSONstring
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class useJACKSONapiToConvertJavaOBJtoJSONstring {
public static void main(String[] args) {
Cat cat = new Cat();
cat.setId(1L);
cat.setName("SiAm");
cat.setColor("Cream");
cat.setEyecolor("Blue");
cat.setBreed("Siamese");
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(cat);
System.out.println("ResultingJSONstring = " + json);
//System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
class Cat


public class Cat {
private Long id;
private String name;
private String color;
private String eyecolor;
private String breed;
public Cat() {
public Cat(Long id, String name) {
this.id = id;
this.name = name;
// Getters & Setters
@Override
public String toString() {
return "Cat{" +
"id=" + id +
", name='" + name +
'\'' +
'}';
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getEyecolor() { return eyecolor;
public void setEyecolor(String eyecolor) { this.eyecolor = eyecolor; }
public String getBreed() { return breed; }
public void setBreed(String breed) { this.breed = breed; }
}

Step 3: RUN useJACKSONapitoConvertJavaOBJtoJSONstring

ResultingJSONstring = {"id":1,"name":"SiAm","color":"Cream","eyecolor":"Blue","breed":"Siamese"}

GSON API example

Find the best examples of Java code snippets using com.google.gson.

The below example shows how to use GSON API to convert a Java Object into a JSON String. 

Step 1: Include the GSON JAR files into your classpath

When using MAVEN for dependency management (recommended) you can include the following dependency to download JAR files, any dependency for GSON and automatically include in your project’s classpath as follows:

Add the following dependency to the pom file: 

<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>

Step 2: Create class UseGSONapitoConvertJavaOBJtoJASONstring

call the GSON API using: Gson gson = new Gson();

This example uses the following code: class UseGSONapitoConvertJavaOBJtoJASONstring
import com.google.gson.Gson;
public class UseGSONapitoConvertJavaOBJtoJASONstring{
public static void main(String args[]) {
CatDetails user = new CatDetails("SiAm",
"Siamese",
"[email protected]",
9,
2129991234L,
"NewCatadonia",
true);
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
}

Class CatDetails

/**
* Java Program to map a Java object to JSON String using GSON library.
*/
class CatDetails {
private String name;
private String breed;
private String email;
private int catlives;
private long phone;
private String city;
private boolean likesMice;

public CatDetails(String name, String breed, String email, int catlives, long phone,
String city, boolean likesMice) {
super();
this.name = name;
this.email = email;
this.catlives = catlives;
this.phone = phone;
this.city = city;
this.likesMice = likesMice;
this.breed = breed;
//getters & setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getCatlives() {
return catlives;
}
public void setCatlives(int catlives) {
this.catlives = catlives;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
public boolean isLikesMice() {
return likesMice;
}
public void setLikesMice(boolean likesMice) {
this.likesMice = likesMice;
}
}

Result:

Step 3:RUN UseGSONapitoConvertJavaOBJtoJASONstring

{"name":"SiAm","breed":"Siamese","email":"[email protected]","catlives":9,"phone":2129991234,"city":"NewCatadonia","likesMice":true}
Conclusion

Converting a Java Obj to JSON string is simple using JACKSON or GSON API.

In our examples we provided the code to make it easy for you to reproduce in your IDE.

All you need to do is:

  1. Create a new project (Maven is recommended)
  2. Include the JAR files into your classpath by adding dependencies to the pom file.
  3. Create your classes
  4. Use the JACKSON API: ObjectMapper mapper class
  5. call writeValueAsString(ObjToConvert) method by passing object we want to convert into JSON
  6. or
  7. Use GSON API: class Gson
  8.  call toJson(ObjToConvert) method by passing the object we want to convert into JSON;

Run to convert your Java Obj to JSON string.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Introduction to JSON - Java

Introduction to JSON - Java

Learn the fundamentals of parsing and manipulating JSON data with the JSON-Java library.

Programming plays an indispensable role in software development, but while it is effective at systematically solving problems, it falls short in a few important categories. In the cloud and distributed age of software, data plays a pivotal role in generating revenue and sustaining an effective product. Whether configuration data or data exchanged over a web-based Application Programming Interface (API), having a compact, human-readable data language is essential to maintaining a dynamic system and allowing non-programmer domain experts to understand the system.

While binary-based data can be very condensed, it is unreadable without a proper editor or extensive knowledge. Instead, most systems use a text-based data language, such as eXtensive Markup Language (XML), Yet Another Markup Language (YML), or Javascript Object Notation (JSON). While XML and YML have advantages of their own, JSON has become a front-runner in the realm of configuration and Representational State Transfer (REST) APIs. It combines simplicity with just enough richness to easily express a wide variety of data.

While JSON is simple enough for programmers and non-programmers alike to read and write, as programmers, our systems must be able to produce and consume JSON, which can be far from simple. Fortunately, there exist numerous Java JSON libraries that efficiently tackle this task. In this article, we will cover the basics of JSON, including a basic overview and common use cases, as well as how to serialize Java objects into JSON and how to deserialize JSON into Java objects using the venerable Jackson library. Note that entirety of the code used for this tutorial can be found on Github.

The Basics of JSON

JSON did not start out as a text-based configuration language. Strictly speaking, it is actually Javascript code that represents the fields of an object and can be used by a Javascript compiler to recreate an object. At its most elementary level, a JSON object is a set of key-value pairs — surrounded by braces and with a colon separating the key from the value; the key in this pair is a string —surrounded by quotation marks, and the value is a JSON value. A JSON value can be any of the following:

  • another JSON object
  • a string
  • a number
  • the boolean literal true 
  • the boolean literal false 
  • the literal null 
  • an array of JSON values

For example, a simple JSON object, with only string values, could be:

{"firstName": "John", "lastName": "Doe"}

Likewise, another JSON object can act as a value, as well as a number, either of the boolean literals or a null literal, as seen in the following example:

{
  "firstName": "John", 
  "lastName": "Doe",
  "alias": null,
  "age": 29,
  "isMale": true,
  "address": {
    "street": "100 Elm Way",
    "city": "Foo City",
    "state": "NJ",
    "zipCode": "01234"
  }
}

A JSON array is a comma-separated list of values surrounded by square brackets. This list does not contain keys; instead, it only contains any number of values, including zero. An array containing zero values is called an empty array. For example:

{
  "firstName": "John",
  "lastName": "Doe",
  "cars": [
    {"make": "Ford", "model": "F150", "year": 2018},
    {"make": "Subaru", "model": "BRZ", "year": 2016},
  ],
  "children": []
}

JSON arrays may be heterogeneous, containing values of mixed types, such as: 

["hi", {"name": "John Doe"}, null, 125]

It is a highly-followed common convention, though, for arrays to contain the same types of data. Likewise, objects in an array conventionally have the same keys and value types, as seen in the previous example. For example, each value in the cars array has a key make with a string value, a key model with a string value, and a key year with a numeric value.

It is important to note that the order of key-value pairs in a JSON object and the order of elements in a JSON array do not factor into the equality of two JSON objects or arrays, respectively. For example, the following two JSON objects are equivalent:

{"firstName": "John", "lastName": "Doe"}
{"lastName": "Doe", "firstName": "John"}

JSON Files

A file containing JSON data uses the .json file extension and has a root of either a JSON object or a JSON array. JSON files may not contain more than one root object. If more than one object is desired, the root of the JSON file should be an array containing the desired objects. For example, both of the following are valid JSON files:

[
  {"name": "John Doe"},
  {"name": "Jane Doe"}
]


{
  "name": "John Doe",
  "age": 29
}

While it is valid for a JSON file to have an array as its root, it is also common practice for the root be an object with a single key containing an array. This makes the purpose of the array explicit:

{
  "accounts": [
    {"name": "John Doe"},
    {"name": "Jane Doe"}
  ]
}

Advantages of JSON

JSON has three main advantages: (1) it can be easily read by humans, (2) it can be efficiently parsed by code, and (3) it is expressive. The first advantage is evident by reading a JSON file. Although some files can become large and complex — containing many different objects and arrays — it is the size of these files that is cumbersome, not the language in which they are written. For example, the snippets above can be easily read without requiring context or using a specific set of tools.

Likewise, code can also parse JSON relatively easily; the entirety of the JSON language can be reduced to a set of simple state machines, as described in the ECMA-404 The JSON Data Interchange Standard. We will see in the following sections that this simplicity has translated into JSON parsing libraries in Java that can quickly and accurately consume JSON strings or files and produce user-defined Java objects.

Lastly, the ease of interpretation does not detract from its expressibility. Nearly any object structure can be recursively reduced to a JSON object or array. Those fields that are difficult to serialize into JSON objects can be stringified and their string value used in place of their object representation. For example, if we wished to store a regular expression as a value, we could do so by simply turning the regular expression into a string.

With an understanding of the basics of JSON, we can now delve into the details of interfacing with JSON snippets and files through Java applications.

Serializing Java Objects to JSON

While the process of tokenizing and parsing JSON strings is tedious and intricate, there are numerous libraries in Java that encapsulate this logic into easy-to-use objects and methods that make interfacing with JSON nearly trivial. One of the most popular among these libraries is FasterXML Jackson.

Jackson centers around a simple concept: the ObjectMapper. An ObjectMapper is an object that encapsulates the logic for taking a Java object and serializing it to JSON and taking JSON and deserializing it into a specified Java object. In the former case, we can create objects the represent our model and delegate the JSON creation logic to the ObjectMapper. Following the previous examples, we can create two classes to represent our model: a person and an address:

public class Person {
    private String firstName;
    private String lastName;
    private String alias;
    private int age;
    private boolean isMale;
    private Address address;
    public Person(String firstName, String lastName, String alias, int age, boolean isMale, Address address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.alias = alias;
        this.age = age;
        this.isMale = isMale;
        this.address = address;
    }
    public Person() {}
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getAlias() {
        return alias;
    }
    public void setAlias(String alias) {
        this.alias = alias;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isMale() {
        return isMale;
    }
    public void setMale(boolean isMale) {
        this.isMale = isMale;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + ", alias=" + alias + ", age=" + age
                + ", isMale=" + isMale + ", address=" + address + "]";
    }
}
public class Address {
    private String street;
    private String city;
    private String state;
    private String zipCode;
    public Address(String street, String city, String state, String zipCode) {
        this.street = street;
        this.city = city;
        this.state = state;
        this.zipCode = zipCode;
    }
    public Address() {}
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getZipCode() {
        return zipCode;
    }
    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }
    @Override
    public String toString() {
        return "Address [street=" + street + ", city=" + city + ", state=" + state + ", zipCode=" + zipCode + "]";
    }
}

The Person and Address classes are both Plain Old Java Objects (POJOs) and do not contain any JSON-specific code. Instead, we can instantiate these classes into objects and pass the instantiated objects to the writeValueAsString method of an ObjectMapper. This method produces a JSON object—represented as a String of the supplied object. For example:

Address johnDoeAddress = new Address("100 Elm Way", "Foo City", "NJ", "01234");
Person johnDoe = new Person("John", "Doe", null, 29, true, johnDoeAddress);

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(johnDoe);

System.out.println(json);

Executing this code, we obtain the following output:

{"firstName":"John","lastName":"Doe","alias":null,"age":29,"address":{"street":"100 Elm Way","city":"Foo City","state":"NJ","zipCode":"01234"},"male":true}

If we pretty print (format) this JSON output using the JSON Validator and Formatter, we see that it nearly matches our original example:

{
"firstName":"John",
"lastName":"Doe",
"alias":null,
"age":29,
"address":{
"street":"100 Elm Way",
"city":"Foo City",
"state":"NJ",
"zipCode":"01234"
},
"male":true
}

By default, Jackson will recursively traverse the fields of the object supplied to the writeValueAsString method, using the name of the field as the key and serializing the value into an appropriate JSON value. In the case of String fields, the value is a string; for numbers (such as int), the result is numeric; for booleans, the result is a boolean; for objects (such as Address), this serialization process is recursively repeated, resulting in a JSON object.

Two noticeable differences between our original JSON and the JSON outputted by Jackson are (1) that the order of the key-value pairs is different and (2) there is a male key instead of isMale. In the first case, Jackson does not necessarily output JSON keys in the same order in which the corresponding fields appear in a Java object. For example, the male key is last key in the outputted JSON even though the isMale field is before the address field in the Person object. In the second case, by default, boolean flags of the form isFooBar result in key-value pairs with a key of the form fooBar.

If we desired the key name to be isMale, as it was in our original JSON example, we can annotate the getter for the desired field using the JsonProperty annotation and explicitly supply a key name:

public class Person {
// ...
@JsonProperty("isMale")
public boolean isMale() {
return isMale;
}
// ...
}

Rerunning the application results in the following JSON string, which matches our desired output:

{
"firstName":"John",
"lastName":"Doe",
"alias":null,
"age":29,
"address":{
"street":"100 Elm Way",
"city":"Foo City",
"state":"NJ",
"zipCode":"01234"
},
"isMale":true
}

In cases where we wish to remove null values from the JSON output (where a missing key implicitly denotes a null value rather than explicitly including the null value), we can annotate the affected class as follows:

@JsonInclude(Include.NON_NULL)
public class Person {
// ...
}

This results in the following JSON string:

{
"firstName":"John",
"lastName":"Doe",
"age":29,
"address":{
"street":"100 Elm Way",
"city":"Foo City",
"state":"NJ",
"zipCode":"01234"
},
"isMale":true
}

While the resulting JSON string is equivalent to the JSON string that explicitly included the null  value, the second JSON string saves space. This efficiency is more applicable to larger objects that have many null fields. 

Serializing Collections

In order to create a JSON array from Java objects, we can pass a Collection object (or any subclass) to the ObjectMapper. In many cases, a List will be used, as it most closely resembles the JSON array abstraction. For example, we can serialize a List of Person objects as follows:

Address johnDoeAddress = new Address("100 Elm Way", "Foo City", "NJ", "01234");
Person johnDoe = new Person("John", "Doe", null, 29, true, johnDoeAddress);

Address janeDoeAddress = new Address("200 Boxer Road", "Bar City", "NJ", "09876");
Person janeDoe = new Person("Jane", "Doe", null, 27, false, janeDoeAddress);

List<Person> people = List.of(johnDoe, janeDoe);

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(people);

System.out.println(json);

Executing this code results in the following output:

[
{
"firstName":"John",
"lastName":"Doe",
"age":29,
"address":{
"street":"100 Elm Way",
"city":"Foo City",
"state":"NJ",
"zipCode":"01234"
},
"isMale":true
},
{
"firstName":"Jane",
"lastName":"Doe",
"age":27,
"address":{
"street":"200 Boxer Road",
"city":"Bar City",
"state":"NJ",
"zipCode":"09876"
},
"isMale":false
}
]

Writing Serialized Objects to a File

Apart from storing the resulting JSON into a String variable, we can write the JSON string directly to an output file using the writeValue method, supplying a File object that corresponds to the desired output file (such as john.json):

Address johnDoeAddress = new Address("100 Elm Way", "Foo City", "NJ", "01234");
Person johnDoe = new Person("John", "Doe", null, 29, true, johnDoeAddress);

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("john.json"), johnDoe);

The serialized Java object can also be written to any OutputStream, allowing the outputted JSON to be streamed to the desired location (e.g. over a network or on a remote file system).

Deserializing JSON Into Java Objects

With an understanding of how to take existing objects and serialize them into JSON, it is just as important to understand how to deserialize existing the JSON into objects. This process is common when deserializing configuration files and resembles its serializing counterpart, but it also differs in some important ways. First, JSON does not inherently retain type information. Thus, looking at a snippet of JSON, it is impossible to know the type of the object it represents (without explicitly adding an extra key, as is the case with the _class key in a MongoDB database). In order to properly deserialize a JSON snippet, we must explicitly inform the deserializer of the expected type. Second, keys present in the JSON snippet may not be present in the deserialized object. For example, if a newer version of an object — containing a new field — has been serialized into JSON, but the JSON is deserialized into an older version of the object.

In order to tackle the first problem, we must explicitly inform the ObjectMapper the desired type of the deserialized object. For example, we can supply a JSON string representing a Person object and instruct the ObjectMapper to deserialize it into a Person object:

String json = "{"firstName":"John","lastName":"Doe","alias":"Jay","
+ ""age":29,"address":{"street":"100 Elm Way","city":"Foo City","
+ ""state":"NJ","zipCode":"01234"},"isMale":true}";

ObjectMapper mapper = new ObjectMapper();
Person johnDoe = mapper.readValue(json, Person.class);
System.out.println(johnDoe);

Executing this snippet results in the following output:

Person [firstName=John, lastName=Doe, alias=Jay, age=29, isMale=true, address=Address [street=100 Elm Way, city=Foo City, state=NJ, zipCode=01234]]

It is important to note that there are two requirements that the deserialized type (or any recursively deserialized types) must have:

  1. The class must have a default constructor
  2. The class must have setters for each of the fields

Additionally, the isMale getter must be decorated with the JsonProperty annotation (added in the previous section) denoting that the key name for that field is isMale. Removing this annotation will result in an exception during deserialization because the ObjectMapper, by default, is configured to fail if a key is found in the deserialized JSON that does not correspond to a field in the supplied type. In particular, since the ObjectMapper expects a male field (if not configured with the JsonProperty annotation), the deserialization fails since there is no field male found in the Person class.

In order to remedy this, we can annotate the Person class with the JsonIgnoreProperties annotation. For example:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
// ...
}

We can then add a new field, such as favoriteColor in the JSON snippet, and deserialize the JSON snippet into a Person object. It is important to note, though, that the value of the favoriteColor key will be lost in the deserialized Person object since there is no field to store the value:

String json = "{"firstName":"John","lastName":"Doe","alias":"Jay","
+ ""age":29,"address":{"street":"100 Elm Way","city":"Foo City","
+ ""state":"NJ","zipCode":"01234"},"isMale":true,"favoriteColor":"blue"}";

ObjectMapper mapper = new ObjectMapper();
Person johnDoe = mapper.readValue(json, Person.class);
System.out.println(johnDoe);

Executing this snippet results in the following output:

Person [firstName=John, lastName=Doe, alias=Jay, age=29, isMale=true, address=Address [street=100 Elm Way, city=Foo City, state=NJ, zipCode=01234]]

Deserializing Collections

In some cases, the JSON we wish to deserialize has an array as its root value. In order to properly deserialize JSON of this form, we must instruct the ObjectMapper to deserialize the supplied JSON snippet into a Collection (or a subclass) and then cast the result to a Collection object with the proper generic argument. In many cases, a List object is used, as in the following code:

String json = "[{"firstName":"John","lastName":"Doe","age":29,"
+ ""address":{"street":"100 Elm Way","city":"Foo City","
+ ""state":"NJ","zipCode":"01234"},"isMale":true},"
+ "{"firstName":"Jane","lastName":"Doe","age":27,"
+ ""address":{"street":"200 Boxer Road","city":"Bar City","
+ ""state":"NJ","zipCode":"09876"},"isMale":false}]";

ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
List<Person> people = (List<Person>) mapper.readValue(json, List.class);

System.out.println(people);

Executing this snippet results in the following output:

[{firstName=John, lastName=Doe, age=29, address={street=100 Elm Way, city=Foo City, state=NJ, zipCode=01234}, isMale=true}, {firstName=Jane, lastName=Doe, age=27, address={street=200 Boxer Road, city=Bar City, state=NJ, zipCode=09876}, isMale=false}]

It is important to note that the cast used above is an unchecked cast since the ObjectMapper cannot verify that the generic argument of List is correct a priori; i.e., that the ObjectMapper is actually returning a List of Person objects and not a List of some other objects (or not a List at all).

Reading JSON From an Input File

Although it is useful to deserialize JSON from a string, it is common that the desired JSON will come from a file rather than a supplied string. In this case, the ObjectMapper can be supplied any InputStream or File object from which to read. For example, we can create a file named john.json on the classpath which contains the following:

{"firstName":"John","lastName":"Doe","alias":"Jay","age":29,"address":{"street":"100 Elm Way","city":"Foo City","state":"NJ","zipCode":"01234"},"isMale":true}

Then, the following snippet can be used to read from this file:

ObjectMapper mapper = new ObjectMapper();
Person johnDoe = mapper.readValue(new File("john.json"), Person.class);
System.out.println(johnDoe);

Executing this snippet results in the following output:

Person [firstName=John, lastName=Doe, alias=null, age=29, isMale=true, address=Address [street=100 Elm Way, city=Foo City, state=NJ, zipCode=01234]]
Conclusion

While programming is a self-evident part of software development, it is not the only skill that developers must possess. In many applications, data drives an application: configuration files create dynamism, and web-service data allows disparate parts of a system to communicate with one another. In particular, JSON has become one of the de facto data languages in many Java applications. Learning not only how this language is structured but how to incorporate JSON into Java applications can add an important set of tools to a Java developer's toolbox.

Originally published on https://dzone.com

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Explore JSON and how JavaScript Objects can be used to access data within JSON data format and output to your web page

Guide to learning how to use JavaScript Objects and JSON data. JSON is the most popular format for data exchange between applications. If you are interested in connected to a web API chances are its JSON formatted. Learn to use AJAX to connect and bring JSON data into your JavaScript!

This course shows you how to work with JSON formatted data, output content, loop JSON data, Parse JSON and a whole lot more.

JSON (JavaScript Object Notation) is a syntax for data. JSON is easier to use than XML and human readable. Most modern web APIs output data in JSON formats. It's a lightweight data interchange format that is quickly becoming the default format for data exchange on internet today! JSON is lightweight, language independent and easy to read and write. JSON is better than XML and more popular!

Within the lessons of this course we will explore

  • JavaScript data types used to hold variables and how they work
  • JSON and how to write JSON data
  • How to add values into a JSON object
  • Accessing JSON data and bringing it into JavaScript
  • JavaScript JSON parse and stringify methods
  • Adding JSON to local storage
  • Retrieving back data within JSON formats, updating and working with JSON
  • Connecting to a web API using fetch
  • Retrieving JSON data from a web API and outputting the results into your web page
  • Iterating threw multiple results from an API
  • Google Spreadsheet data as JSON and how to practice retrieving data
  • All of the source code and resources are in included
  • Explore different methods of working with the JSON data stringify and parsing
  • How JavaScript objects can use Arrays to hold multiple items
  • How JavaScript arrays work and store data

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript and JSON

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Programming Tutorial | Full JavaScript Course for Beginners 2019

The complete beginner’s guide to JSON

The Complete Guide to JSON Web Tokens

JWT Fundamentals for Beginners

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

New ES2019 Features Every JavaScript Developer Should Know

JSON vs XML: How Do They Compare?

JSON vs XML: How Do They Compare?

In this article, we will outline what’s going on, and what you need to know about JSON and XML.

JSON and XML are two human-readable text formats that have emerged as rivals over the years. XML’s purpose is storing and defining documents and data through the optional use of a schema. JSON was almost the exact opposite – a serialization format with requirements so simple they fit on the back of a credit card. But, when should you use one or the other? We have to take into account that XML and JSON have similarities and differences that can affect your application’s performance.

In this article, we will outline what’s going on, and what you need to know about JSON and XML.

Background

JavaScript caused a seismic shift in web development with the creation of Node (which is really server-side JavaScript). Everything from this point on got replaced with REST APIs and JSON. JSON became the most efficient data structure standard in web apps. Web 1.0 was hindered with parsing data structures and caused innovation to slow down, while Web 2.0 created an explosion in productivity and Moore’s Law kicked in. JavaScript, which was considered a dead language at one point, was revived and is now one of the most popular languages in 2019.

Comparing JSON and XML

Similarities:

  • Both are human readable.
  • Both are hierarchal with a values within values format.
  • Both can be parsed and used by a number of languages.

Differences:

JSON

  • Shorter
  • Quicker to parse
  • Uses arrays
  • Parsed by a standard JavaScript function
  • Data interchange format

XML

  • Needs an XML parser.
  • Longer to parse.
  • Doesn’t use Arrays!!
Which should I consider?

Everyone has their own opinion about JSON and XML. As a developer, I more or less stick to JSON in my projects unless an API requires XML parsing.

XML is still being used actively in web publishing to create interactive pages. It’s also used for searching the web, metadata and pervasive computing, which is another way to say wireless devices, like cell phones.

Depending on the type of application, it will vary based on what best fits your application to access information.

What’s going on

As applications and platforms evolved, efficiency and performance have been the status quo in priority. APIs evolved over the years to become leaner, and JSON has overtaken XML as the preferred format among developers and technology stacks.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

The complete beginner’s guide to JSON

Converting JSON to CSV in Java

How to use JSON.stringify() and JSON.parse() in JavaScript

The Complete Guide to JSON Web Tokens

Stateless Authentication with JSON Web Tokens

Parsing JSON in Flutter

Authenticate a Node ES6 API with JSON Web Tokens