JSON – Advantages and Disadvantages

Back to Blog
JSON versus XML - JSON web service php

JSON – Advantages and Disadvantages

JSON (JavaScript Object Notation) is light-weighted designed such that humans can easily read data interchange and it’s execution.

The JSON format was originally specified and developed by Douglas Crockford and is described in RFC 4627 license. The JSON filename extension is .json.

JSON is based on the object notation of the JAVASCRIPT language and its standard only. It does not require JavaScript to read or write because it is made in text format which is language independent and can be run everywhere. JSON notation contains these basic elements which have JSON advantages in JAVASCRIPT:

1. Objects:Objects begin and end with curly braces ({}).

2. Object Members: Members consist of strings and values commas(,) separated

3. Arrays: Arrays begin and end with braces and contain different values.

4. Values:A value can be a string, can be an object, an array, or the literals

5. Strings:Strings are surrounded by double quotes and contain the Unicode colon (:). Members are separated by commas(,).Values are separated by commas(,). true, false or null.character or common backslash escapes.

JSON Example


{
  "first_name": "Rajeev",
  "last_name": "Sharma",
  "email_address": "rajeev@ezeelive.com",
  "is_alive": true,
  "age": 30,
  "height_cm": 185.2,
  "billing_address": {
    "address": "502, Main Market, Evershine City, Evershine, Vasai East",
    "city": "Vasai Raod, Palghar",
    "state": "Maharashtra",
    "postal_code": "401208"
  },
  "shipping_address": {
    "address": "Ezeelive Technologies, A-4, Stattion Road, Oripada, Dahisar East",
    "city": "Mumbai",
    "state": "Maharashtra",
    "postal_code": "400058"
  },
  "phone_numbers": [
   {
   "type": "home",
   "number": "9975666694"
   },
   {
   "type": "office",
   "number": "9822117730"
   }
 ],
 "date_of_birth": null
}

JSON Advantages

Here are top advantages of JSON every developer should know:

1. JSON is Faster:

JSON syntax is very easy to use. We have to use only -> as a syntax which provides us an easy parsing of the data and faster execution of the data. Since its syntax is very small and light weighted that’s the reason that it executes the response in the faster way.

2. Schema Support:

It has the wide range of supported browser compatibility with the operating systems so the applications made with the coding of JSON doesn’t require much effort to make it all browser compatible. During development, the developer thinks for the different browsers but JSON provides that functionality.

Ezeelive Technologies - Rest API Security
Rest API Security – How secure JSON data transfer

3. Server Parsing:

On the server side parsing is the important part that developers want if the parsing will be fast on the server side then the only user can get the fast response of their response so in this case JSON server-side parsing is the strong point that indicates us to use the JSON on the server side.

4. Tool for sharing data:

JSON is the best tool for the sharing data of any size even audio, video etc. This is because JSON stores the data in the arrays so data transfer makes easier. For this reason, JSON is a superior file format for web APIs and for web development.

JSON Disadvantages

First and foremost, in JSON has no error handling for JSON calls. If the dynamic script insertion works, you get called and will get the response perfectly.

If not inserted, nothing happens. It just fails silently. For example, you are not able to catch a 404 error from the server, Nor can you cancel or restart the request. You can, however, timeout after waiting a reasonable amount of time.

Another major drawback of JSON is that it can be quite dangerous if used with untrusted services or untrusted browsers, because a JSON service returns a JSON response wrapped in a function call, which will be executed by the browser if it will be used with untrusted browser it can be hacked, this makes the hosting Web Application Vulnerable to a variety of attacks.

If you are going to use JSON services, it’s very important to be aware of the threats which JSON have in that and also be aware of the things which can protect it. JSON development has limited supported tools for use.

JSON vs BSON

JSON vs BSON
JSON vs BSON

JSON is a widely used text-based data format that is human-readable and easy to work with in many programming languages.

BSON, on the other hand, is a binary format that is more efficient in terms of size and parsing speed, making it suitable for specific use cases where performance and compactness are priorities, such as in certain database systems.

Designed to address the limitations of JSON, BSON is widely associated with MongoDB, where it serves as the primary data storage format. It provides additional features such as type information, making it more versatile for various use cases.

The choice between JSON and BSON depends on the specific requirements of your application.

Advantages of BSON

  1. Compact Representation: By using a binary format, BSON reduces the overhead associated with text-based formats like JSON, saving storage space and bandwidth.
  2. Faster Processing: Its compact and structured nature allows for quicker parsing and serialization compared to JSON.
  3. Rich Data Types: The support for additional types like dates, binary data, and ObjectId simplifies handling complex data structures.
  4. Schema Flexibility: While self-describing, BSON remains schema-agnostic, allowing developers to work with dynamic and evolving data models.

Use Cases of BSON

  • MongoDB: BSON is the core data representation format used by MongoDB for storing and transferring documents. It leverages BSON’s efficient traversal and rich data type support.
  • Data Transmission: BSON is suitable for scenarios requiring efficient data exchange between systems, particularly when complex data types are involved.
  • Embedded Systems: BSON’s compactness makes it a good choice for resource-constrained environments.

Limitations of BSON

  1. Overhead for Small Documents: For very small documents, BSON may introduce slightly more overhead than JSON due to metadata like type information and size.
  2. Readability: As a binary format, BSON is not human-readable, unlike JSON. Debugging and manual inspection require specialized tools.
  3. Size Expansion: While BSON is compact for large, complex documents, it may expand the size of simple structures compared to JSON.

JSON (JavaScript Object Notation) and BSON (Binary JSON) are both data interchange formats used to represent structured data in a human-readable and machine-readable way, but they have key differences:

Key PointsJSONBSON
Serialization Format
JSON is a text-based format. It uses plain text to represent data using a combination of key-value pairs, arrays, and primitive data types like strings, numbers, booleans, and null. JSON is easy for humans to read and write.BSON, on the other hand, is a binary format. It encodes data in a compact binary form, which is more efficient for storage and transmission but not human-readable like JSON.
Efficiency
JSON is less efficient in terms of size and performance compared to BSON. JSON data is typically larger in size because it includes human-readable whitespace and uses a text-based representation.BSON is more efficient in terms of both size and parsing performance. It is designed to be compact and can be parsed more quickly by machines.
Data Types
JSON supports a limited set of data types, including strings, numbers, booleans, arrays, objects, null, and nested combinations of these types.BSON supports a wider range of data types, including additional data types like dates, binary data, and specific numerical types. This makes BSON more suitable for representing data in some programming languages with richer type systems.
Extensibility
JSON is a well-defined standard with a fixed set of data types. Extending JSON typically involves adding custom fields or using conventions within the data itself.BSON allows for more flexibility in extending the data format by supporting additional data types, which can be useful for representing data in certain contexts.
Use Cases
JSON is commonly used for data interchange between web services, configuration files, and settings where human readability is important. It is widely supported in various programming languages.BSON is often used in situations where performance and compactness are critical, such as in databases like MongoDB, which uses BSON as its native storage format.
Example
{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "courses": ["Math", "History", "Science"]
}

\x16\x00\x00\x00
\x02hello\x00\x06\x00\x00\x00world\x00
\x00

JSON vs XML

JSON and XML (Extensible Markup Language) are both data interchange formats used to represent structured data, but they have different characteristics and are used in various contexts. Here’s a comparison of JSON and XML:

Key PointsJSONXML
Syntax
JSON uses a simple and compact syntax with key-value pairs. It is easier for humans to read and write due to its minimalistic and less verbose structure.XML uses a more complex markup language with tags and attributes, which can make it more verbose and harder for humans to read and write.
Data Types
JSON supports basic data types such as strings, numbers, booleans, arrays, objects, and null values. It represents data in a hierarchical manner.XML is more flexible in terms of defining custom data types through Document Type Definitions (DTD) or XML Schema Definitions (XSD). It can represent data in a hierarchical structure as well.
Readability
JSON is generally considered more readable by both humans and machines due to its concise and straightforward syntax.XML can be less readable for humans because of its tag-based structure and verbosity.
Size Efficiency
JSON is usually more compact in terms of data size compared to XML. This can be advantageous in situations where bandwidth or storage is limited.XML tends to be more verbose, which can result in larger file sizes compared to JSON representations of the same data.
Parsing and Processing
JSON is typically faster to parse and process because of its simpler structure. Most programming languages have efficient JSON parsers.XML parsing can be more resource-intensive due to its complex and extensible nature, especially when using DTDs or XSDs.
Schema Validation
JSON does not have built-in schema validation, but it can be validated using external tools or libraries.XML can be validated against predefined schemas using DTD or XSD, ensuring data conformity.
Namespace Support
JSON does not natively support namespaces, which can be important in certain XML use cases.XML supports namespaces, making it suitable for scenarios where data needs to be uniquely identified in a complex hierarchy.
Use Cases
JSON is commonly used for web APIs, configuration files, and data exchange between modern web applications and services. It’s well-suited for representing structured data.XML is often used in contexts where data needs to be highly structured, self-descriptive, or validated against a schema. It’s prevalent in document-oriented applications, including publishing, finance, and some legacy systems.

JSON and XML are both useful data interchange formats, but JSON is generally preferred for modern web development and API integration due to its simplicity, readability, and efficient parsing. XML is still relevant, particularly in scenarios where complex data structures, document hierarchies, or specific standards and namespaces are required. Your choice between JSON and XML should depend on your project’s specific requirements and the ecosystem you are working in.

JSON vs YAML

JSON and YAML (YAML Ain’t Markup Language) are both data serialization formats used for representing structured data. They serve similar purposes but have some differences that make each suitable for different use cases. Here’s a comparison of JSON and YAML:

Key PointsJSONYAML
Syntax
Uses a simple and strict syntax with key-value pairs separated by colons (:), arrays represented with square brackets ([]), and objects (associative arrays) represented with curly braces ({}). JSON is easy for machines to parse but less human-readable due to the use of punctuation.Employs a more human-readable, indentation-based syntax that uses colons and spaces. YAML uses whitespace and indentation to define the structure of data, which makes it more intuitive for humans but can lead to formatting issues if not used consistently.
Readability
While JSON is machine-friendly and widely supported, its strict punctuation-based syntax can be less readable for humans, especially for complex nested structures.YAML is designed with human readability in mind. Its indentation-based structure is more natural to read and write for humans, which makes it a good choice for configuration files and documents.
Complexity
Well-suited for representing simple to moderately complex data structures. It excels at representing data in key-value pairs and arrays.Can handle complex data structures with ease due to its nested, hierarchical nature. It is especially useful for representing configuration files with deep nesting.
Comments
Does not support comments within the data itself. Comments are typically placed in separate documentation.Supports comments using the # symbol, allowing you to include explanatory notes directly within the data.
Data Types
Supports basic data types, including strings, numbers, booleans, null, arrays, and objects. It doesn’t have native support for binary data.Supports basic data types similar to JSON, including strings, numbers, booleans, null, and arrays. Additionally, YAML has more flexible handling of data types and allows custom data types to be defined.
Usage
Commonly used for data interchange in web APIs, configuration files, and data storage. It’s also used in NoSQL databases and JavaScript-based applications.Frequently used for configuration files, data serialization in configuration management tools (e.g., Ansible and Kubernetes), and human-readable data storage.
Compatibility
Supported by a wide range of programming languages, making it easy to work with JSON data in various environments.While well-supported in many programming languages, YAML parsers and libraries may not be as prevalent as those for JSON.

JSON and YAML both have their strengths, with JSON being a good choice for machine-to-machine communication and data interchange, while YAML excels in human-readable configuration files and documents. The choice between them should depend on your specific use case and the balance between machine-friendliness and human-friendliness that your project requires.

JSON vs JSONB

JSON and JSONB (JSON Binary) are both data storage formats used in relational databases, but they have distinct differences in how they store and manage JSON data. Here’s a comparison of JSON vs. JSONB:

Key PointsJSONJSONB
Data Storage
In a relational database, JSON data is stored as text in a structured column. While JSON is human-readable and flexible, it requires parsing when querying or updating specific elements within the JSON structure.JSONB stores JSON data in a binary format, which is optimized for efficient storage and retrieval. It uses a compact binary representation that allows for fast indexing and querying of specific JSON elements.
Performance
Retrieving specific elements from JSON data can be slower because the database needs to parse the entire JSON document to access the requested data.JSONB is designed for performance. It provides faster query performance, especially when you need to search or index specific JSON attributes. This is because JSONB stores the data in a more efficient binary format.
Size
JSON data is typically larger in size compared to JSONB due to its human-readable text representation.JSONB data is smaller in size because it uses a binary format, making it more space-efficient.
Querying and Indexing
While relational databases often provide functions and operators for querying JSON data in columns, the performance may be suboptimal for complex queries, especially on large datasets.JSONB allows for efficient indexing of specific JSON elements, enabling complex queries to perform better. This makes JSONB suitable for scenarios where you need to search or filter data within JSON documents.
Validation and Constraints
JSON data may not enforce strict validation or constraints on the structure of JSON documents, allowing for potentially invalid or inconsistent data to be stored.JSONB doesn’t enforce validation or constraints either, but it implicitly validates the stored JSON data during conversion to its binary format. This means that JSONB data is always well-formed JSON.
Data Modification
Modifying specific elements within a JSON document can be more complex and requires parsing and updating the entire document.JSONB allows for efficient updates of specific elements within a JSON document because it doesn’t need to rewrite the entire binary representation.
Use Cases
JSON is often used when the human readability of the JSON data is important, and the data doesn’t need to be frequently queried or indexed.JSONB is recommended when performance, efficient querying, and indexing of JSON data are essential, especially in scenarios where you have large volumes of JSON data in a relational database.

The choice between JSON and JSONB in a relational database depends on your specific requirements. JSONB is generally favored for scenarios where query performance, efficient indexing, and storage space are important, while JSON is more suitable when human readability of the data is a priority and performance is less critical.

How to secure data and prevent JSON Vulnerability & Hijacking

Secure data prevent json vulnerability hijacking
JSON prevent Cross Site Request Forgery (CSRF)

JSON is not fully secure as we think in the web world, Cross Site Request Forgery (CSRF) in JSON Array hack allow grab sensitive user data from an unsuspecting user.

This is major in exposing a JSON service which contains JSON array, sensitive data, responds to GET requests, Request with JavaScript enabled, request supports the __defineSetter__ method etc.

In Above we had discussed the issue, Now will discuss how to prevent CRSF Attack and Secure sensitive data in following points:

  1. Most important, All the request method has to be POST and Prevent your code to accept only POST Request.

$.ajax ({
    url: '//yourdomainname.com/login',
    dataType: 'json',
    data: JSON.stringify(dataObject),
    contentType: 'application/json; charset=utf-8',
    type: 'POST',
    success: function (jsonData) {
        // Success callback
    },
    error: function() {
        //any error to be handled
    }
 });
  1. Add unique CSRF token in request prevent the application from cookie hijacking and bad requests.
  2. Always use secure transfer protocol (HTTPS) in requests.
  3. Check special header such as the X-Requested-With: XMLHttpRequest or Content-Type: application/json before serving the response to the request.
  4. Code testing tools like checkmarx, SonarQube, Burp Suite etc. will help to application security.
  5. User Access log should be managed to check which user activities.
  6. Use API and End URL authentication to validate current endpoint.
  7. Should use token-based API access such as JSON Web Tokens (JWT).
  8. Implement Error handling and Do not provide any technical detail in API call.
  9. JSON Validation: PHP 8.3 introduce built-in json validation function. It allows to check if a string is syntactically valid JSON, while being more efficient than json_decode():

PHP < 8.2


function json_validate(string $string): bool {
    json_decode($string);

    return json_last_error() === JSON_ERROR_NONE;
}

var_dump(json_validate('{ "data": { "name": "nitin" } }')); // true

PHP 8.3


var_dump(json_validate('{ "data": { "name": "nitin" } }')); // true

Example of JSON Web Service PHP with MySQL

MySQL Database :


create database IF NOT EXISTS `ezeelive_json_rest_tutes`

--
-- Table structure for table `customer`
--

CREATE TABLE IF NOT EXISTS `customer` (
`customer_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email_address` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`is_active` text NOT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO `customer` (`customer_id`, `first_name`, `last_name`, `email_address`, `password`, `is_active`) VALUES
(1, 'Rajeev', 'Sharma', 'rajeev@ezeelive.com', 'e10adc3949ba59abbe56e057f20f883e', 1),
(2, 'Nitin', 'Bhardwaj', 'nitin@ezeelive.com', '6d071901727aec1ba6d8e2497ef5b709', 0);

config.php


<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('ezeelive_json_rest_tutes', $conn);

json_rest_customer_list.php


<?php
include_once('config.php');
$result = mysql_query("SELECT customer_id, first_name, last_name, email_address, is_active FROM `customer` ORDER BY customer_id ASC;");
if(isset($result))
{
$data =array();
while($d = mysql_fetch_array($result)){
extract($d);
$data[] = array("customer_id" => $customer_id, "first_name" => $first_name, "last_name" => $last_name, "email_address" => $email_address, "is_active" => $is_active);
}
$json = array("status" => 1, "info" => $data);
}else{
$json = array("status" => 0, "msg" => "An error occurred.");
}
@mysql_close($conn);

// Output json header
header('Content-type: application/json');
echo json_encode($json);

JSON Output:


{
  status: 1
  info: [2]
    0:{
     customer_id: "1",
     first_name: "Rajeev",
     last_name: "Sharma",
     email_address: "rajeev@ezeelive.com",
     is_active: "1"
     },
    1:{
     customer_id: "2",
     first_name: "Nitin",
     last_name: "Bhardwaj",
     email_address: "nitin@ezeelive.com",
     is_active: "0"
     }
}

JSON in Python

In Python, the json module allows you to work with JSON (JavaScript Object Notation) data, which is commonly used for data exchange. You can use it to parse JSON data, convert Python objects to JSON, and vice versa.

Here’s a quick guide on how to use the json module:

import json

Convert Python object to JSON (serialization):

To convert a Python object (like a dictionary) into a JSON string, use json.dumps():


data = {"name": "John", "age": 30, "city": "New York"}
json_string = json.dumps(data)
print(json_string)

Convert JSON string to Python object (deserialization):

To convert a JSON string back into a Python object (like a dictionary), use json.loads():


json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data)

Read and write JSON to/from files:

Writing JSON to a file:


data = {"name": "John", "age": 30, "city": "New York"}
with open("data.json", "w") as json_file:
    json.dump(data, json_file)

Reading JSON from a file:


with open("data.json", "r") as json_file:
    data = json.load(json_file)
print(data)

JSON in Golang

In Go (Golang), the encoding/json package is used to work with JSON data. You can use it to marshal (convert Go objects to JSON) and unmarshal (convert JSON to Go objects) data.

Here’s how you can use it:

Import the encoding/json package:

import "encoding/json"

Convert Go object to JSON (marshalling):

To convert a Go struct or map to JSON, use the json.Marshal() function.


package main

import (
   "encoding/json"
   "fmt"
)

type Person struct {
   Name string `json:"name"`
   Age  int    `json:"age"`
   City string `json:"city"`
}

func main() {
   // Create a Go struct
   person := Person{Name: "John", Age: 30, City: "New York"}

   // Marshal the struct into JSON
   jsonData, err := json.Marshal(person)
   if err != nil {
     fmt.Println(err)
     return
   }

   // Print the JSON string
   fmt.Println(string(jsonData))
}

Convert JSON to Go object (unmarshalling):

To convert JSON into a Go struct, use json.Unmarshal().


package main

import (
   "encoding/json"
   "fmt"
)

type Person struct {
   Name string `json:"name"`
   Age  int    `json:"age"`
   City string `json:"city"`
}

func main() {
   // JSON data
   jsonString := `{"name": "John", "age": 30, "city": "New York"}`

   // Unmarshal the JSON into a Go struct
   var person Person
   err := json.Unmarshal([]byte(jsonString), &person)
   if err != nil {
      fmt.Println(err)
      return
   }

   // Print the struct
   fmt.Println(person)
}

Read and write JSON from/to files:

Writing JSON to a file:


package main

import (
   "encoding/json"
   "fmt"
   "os"
)

type Person struct {
   Name string `json:"name"`
   Age  int    `json:"age"`
   City string `json:"city"`
}

func main() {
   // Create a Go struct
   person := Person{Name: "John", Age: 30, City: "New York"}

   // Open file for writing
   file, err := os.Create("data.json")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   // Write JSON data to the file
   encoder := json.NewEncoder(file)
   err = encoder.Encode(person)
   if err != nil {
      fmt.Println(err)
   }
}

Reading JSON from a file:


package main

import (
   "encoding/json"
   "fmt"
   "os"
)

type Person struct {
   Name string `json:"name"`
   Age  int    `json:"age"`
   City string `json:"city"`
}

func main() {
   // Open JSON file for reading
   file, err := os.Open("data.json")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   // Read the JSON data into a struct
   var person Person
   decoder := json.NewDecoder(file)
   err = decoder.Decode(&person)
   if err != nil {
      fmt.Println(err)
      return
   }

   // Print the struct
   fmt.Println(person)
}

Summary of Key Functions:

  • json.Marshal() – Converts Go objects to JSON.
  • json.Unmarshal() – Converts JSON to Go objects.
  • json.NewEncoder() – Creates a new encoder for writing JSON to an io.Writer (e.g., file).
  • json.NewDecoder() – Creates a new decoder for reading JSON from an io.Reader (e.g., file).

JSON in NodeJS

In Node.js, working with JSON is straightforward since it is natively supported. You can use the built-in JSON object to parse JSON data and convert JavaScript objects to JSON format.

Here’s how you can use JSON in Node.js:

Convert JavaScript object to JSON (Serialization):

To convert a JavaScript object to a JSON string, use JSON.stringify().


const person = {
  name: "John",
  age: 30,
  city: "New York"
};

// Convert JavaScript object to JSON string
const jsonString = JSON.stringify(person);

console.log(jsonString);

Convert JSON string to JavaScript object (Deserialization):

To parse a JSON string back into a JavaScript object, use JSON.parse().


const jsonString = '{"name": "John", "age": 30, "city": "New York"}';

// Parse JSON string into JavaScript object
const person = JSON.parse(jsonString);

console.log(person);

Read and write JSON to/from files:

In Node.js, you can read and write JSON files using the fs module.

Writing JSON to a file:

You can write a JSON string to a file using fs.writeFile() or fs.writeFileSync().


const fs = require('fs');

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

// Write JSON string to a file
fs.writeFile('data.json', JSON.stringify(person, null, 2), (err) => {
  if (err) {
    console.error('Error writing to file', err);
  } else {
    console.log('Data saved to data.json');
  }
});

Reading JSON from a file:

You can read a JSON file using fs.readFile() or fs.readFileSync().


const fs = require('fs');

// Read JSON data from a file
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file', err);
  } else {
    const person = JSON.parse(data);
    console.log(person);
  }
});

Alternatively, you can use the synchronous version:


const fs = require('fs');

// Synchronously read JSON from a file
const data = fs.readFileSync('data.json', 'utf8');
const person = JSON.parse(data);

console.log(person);

Key Methods:

  • JSON.stringify() – Converts a JavaScript object to a JSON string.
  • JSON.parse() – Converts a JSON string to a JavaScript object.
  • fs.writeFile() – Asynchronously writes data to a file.
  • fs.writeFileSync() – Synchronously writes data to a file.
  • fs.readFile() – Asynchronously reads data from a file.
  • fs.readFileSync() – Synchronously reads data from a file.

JSON in JAVA

In Java, JSON can be processed using libraries like Jackson, Gson, or org.json. Here’s a comprehensive guide to working with JSON in Java using these libraries:

1. Using Jackson (Preferred for Most Projects)

Jackson is a widely used library for JSON serialization and deserialization in Java.

Add Dependency:

Maven:


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

Usage:


import com.fasterxml.jackson.databind.ObjectMapper;

class Person {
    private String name;
    private int age;
    private String city;

    // Default constructor (needed for Jackson)
    public Person() {}

    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

public class JacksonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // Serialize Java object to JSON
        Person person = new Person("John", 30, "New York");
        String jsonString = objectMapper.writeValueAsString(person);
        System.out.println("Serialized JSON: " + jsonString);

        // Deserialize JSON to Java object
        String jsonInput = "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}";
        Person deserializedPerson = objectMapper.readValue(jsonInput, Person.class);
        System.out.println("Deserialized Name: " + deserializedPerson.getName());
    }
}

2. Using Gson

Gson is another popular library for JSON handling.

Add Dependency:

Maven:


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

Usage:


import com.google.gson.Gson;

class Person {
    private String name;
    private int age;
    private String city;

    // Default constructor
    public Person() {}

    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

public class GsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();

        // Serialize Java object to JSON
        Person person = new Person("John", 30, "New York");
        String jsonString = gson.toJson(person);
        System.out.println("Serialized JSON: " + jsonString);

        // Deserialize JSON to Java object
        String jsonInput = "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}";
        Person deserializedPerson = gson.fromJson(jsonInput, Person.class);
        System.out.println("Deserialized Name: " + deserializedPerson.getName());
    }
}

3. Using org.json

The org.json library provides a simple way to work with JSON objects and arrays.

Add Dependency:

Maven:


<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

Usage:


import org.json.JSONObject;

public class OrgJsonExample {
    public static void main(String[] args) {
        // Create JSON object
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "John");
        jsonObject.put("age", 30);
        jsonObject.put("city", "New York");

        System.out.println("Serialized JSON: " + jsonObject.toString());

        // Parse JSON string
        String jsonInput = "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}";
        JSONObject parsedJson = new JSONObject(jsonInput);
        System.out.println("Deserialized Name: " + parsedJson.getString("name"));
    }
}

4. Comparing Libraries

FeatureJacksonGsonorg.json
PerformanceHighHighModerate
Ease of UseSimpleSimpleSimple
FlexibilityHighly FlexibleFlexibleBasic
AnnotationsYes (e.g., @JsonProperty)LimitedNone
CustomizationExtensiveModerateMinimal

5. Reading and Writing JSON Files

You can use any library to read/write JSON files in combination with java.io or java.nio:

Example with Jackson:


import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;

public class FileExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // Write JSON to file
        Person person = new Person("John", 30, "New York");
        objectMapper.writeValue(new File("person.json"), person);

        // Read JSON from file
        Person readPerson = objectMapper.readValue(new File("person.json"), Person.class);
        System.out.println("Read Name: " + readPerson.getName());
    }
}

JSON in ASP.NET

In ASP.NET (including ASP.NET Core), JSON is commonly used for data exchange in web APIs and applications. ASP.NET Core natively supports JSON serialization and deserialization through the System.Text.Json library (recommended) or Newtonsoft.Json (optional).

1. JSON in ASP.NET Core

Setting Up a Web API Project

  1. Create a new ASP.NET Core Web API project.
    
    dotnet new webapi -n JsonExample
    cd JsonExample
    
  2. Add dependencies if needed. By default, ASP.NET Core uses System.Text.Json for JSON handling, but you can add Newtonsoft.Json if required:
    
    dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
    

2. JSON Serialization and Deserialization

System.Text.Json (Default)

Serialization (Object to JSON):


using System.Text.Json;

var person = new
{
    Name = "John",
    Age = 30,
    City = "New York"
};

// Serialize to JSON string
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);

Deserialization (JSON to Object):


using System.Text.Json;

string jsonString = "{\"Name\":\"John\",\"Age\":30,\"City\":\"New York\"}";

// Deserialize JSON string to object
var person = JsonSerializer.Deserialize<Person>(jsonString);

Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.City}");

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

Newtonsoft.Json (Optional)

Serialization (Object to JSON):


using Newtonsoft.Json;

var person = new
{
    Name = "John",
    Age = 30,
    City = "New York"
};

// Serialize to JSON string
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine(jsonString);

Deserialization (JSON to Object):


using Newtonsoft.Json;

string jsonString = "{\"Name\":\"John\",\"Age\":30,\"City\":\"New York\"}";

// Deserialize JSON string to object
var person = JsonConvert.DeserializeObject<Person>(jsonString);

Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.City}");

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

3. JSON in ASP.NET Core Web API

Model Definition


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

Controller Example


using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class PersonController : ControllerBase
{
    // GET endpoint to return JSON
    [HttpGet]
    public IActionResult GetPerson()
    {
        var person = new Person
        {
            Name = "John",
            Age = 30,
            City = "New York"
        };
        return Ok(person);
    }

    // POST endpoint to accept JSON
    [HttpPost]
    public IActionResult SavePerson([FromBody] Person person)
    {
        return Ok($"Received person: {person.Name}, Age: {person.Age}, City: {person.City}");
    }
}

4. Testing the Web API

  • Run the application:
    dotnet run
  • Use tools like Postman or curl to test.

GET Request:


curl -X GET //localhost:5000/api/person

Response:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

POST Request:


curl -X POST //localhost:5000/api/person -H "Content-Type: application/json" -d '{"name":"Jane","age":25,"city":"Los Angeles"}'

Response:


Received person: Jane, Age: 25, City: Los Angeles

5. Customizing JSON Serialization

System.Text.Json Customization

You can customize JSON handling using JsonSerializerOptions.


var options = new JsonSerializerOptions
{
    WriteIndented = true, // Pretty-print JSON
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // CamelCase naming
};

string jsonString = JsonSerializer.Serialize(person, options);

Using Newtonsoft.Json

Add the NewtonsoftJson package and configure it in Startup.cs or Program.cs.


builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
    });

6. JSON File Handling

Reading JSON from a File:


using System.IO;
using System.Text.Json;

var jsonString = File.ReadAllText("person.json");
var person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");

Writing JSON to a File:


using System.IO;
using System.Text.Json;

var person = new Person { Name = "John", Age = 30, City = "New York" };
string jsonString = JsonSerializer.Serialize(person);
File.WriteAllText("person.json", jsonString);

7. JSON Response Formatting

In ASP.NET Core, JSON response formatting can be configured in Program.cs.


builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        options.JsonSerializerOptions.WriteIndented = true;
    });

This covers JSON handling in ASP.NET Core, including serialization, deserialization, file handling, and customization.

JSON in Ruby

In Ruby, handling JSON is straightforward thanks to the built-in json library. Here’s a comprehensive guide to working with JSON in Ruby:

1. JSON Basics

Loading the JSON Library

Ruby includes the json library in its standard library. To use it, you need to require it:

require 'json'

2. JSON Serialization (Convert Ruby Object to JSON)

Use JSON.generate or to_json (available after requiring json) to convert Ruby objects to JSON strings.

require 'json'

# Ruby hash
person = { name: "John", age: 30, city: "New York" }

# Convert Ruby hash to JSON string
json_string = JSON.generate(person)
puts json_string

# Alternative method using `to_json`
puts person.to_json

Output:

{"name":"John","age":30,"city":"New York"}

3. JSON Deserialization (Convert JSON to Ruby Object)

Use JSON.parse to convert JSON strings into Ruby objects (typically hashes).

require 'json'

# JSON string
json_string = '{"name":"Jane","age":25,"city":"Los Angeles"}'

# Parse JSON string to Ruby hash
person = JSON.parse(json_string)

puts person['name']  # Output: Jane
puts person['age']   # Output: 25
puts person['city']  # Output: Los Angeles

Default Behavior:

  • JSON objects become Ruby hashes.
  • JSON arrays become Ruby arrays.

4. Reading and Writing JSON Files

Write JSON to a File


require 'json'

person = { name: "Alice", age: 28, city: "Chicago" }

# Write JSON to a file
File.open("person.json", "w") do |file|
  file.write(JSON.pretty_generate(person)) # Pretty-print for readability
end

Read JSON from a File

require 'json'

# Read JSON from a file
json_data = File.read("person.json")
person = JSON.parse(json_data)

puts person['name']  # Output: Alice

5. Pretty-Printing JSON

Use JSON.pretty_generate to create a human-readable JSON string.

require 'json'

person = { name: "John", age: 30, city: "New York" }

# Pretty-print JSON
pretty_json = JSON.pretty_generate(person)
puts pretty_json

Output:


{
  "name": "John",
  "age": 30,
  "city": "New York"
}

6. Customizing JSON Serialization

You can define custom behavior for JSON serialization by overriding the to_json method in your Ruby classes.


require 'json'

class Person
  attr_accessor :name, :age, :city

  def initialize(name, age, city)
    @name = name
    @age = age
    @city = city
  end

  # Custom JSON serialization
  def to_json(*options)
    {
      name: @name,
      age: @age,
      city: @city
    }.to_json(*options)
  end
end

person = Person.new("John", 30, "New York")
puts person.to_json

Output:


{"name":"John","age":30,"city":"New York"}

7. Parsing JSON with Symbols as Keys

By default, JSON.parse uses strings as hash keys. To use symbols instead:


require 'json'

json_string = '{"name":"Jane","age":25,"city":"Los Angeles"}'

# Parse JSON with symbols as keys
person = JSON.parse(json_string, symbolize_names: true)

puts person[:name]  # Output: Jane

8. Handling Complex Data Structures

You can serialize and deserialize nested data structures like arrays and hashes.


require 'json'

# Nested Ruby structure
data = {
  people: [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 }
  ]
}

# Serialize to JSON
json_string = JSON.generate(data)
puts json_string

# Deserialize JSON
parsed_data = JSON.parse(json_string)
puts parsed_data['people'][0]['name']  # Output: John

9. Error Handling

Always handle errors when parsing JSON to prevent crashes.


require 'json'

begin
  json_string = '{"name":"John", "age":30'
  person = JSON.parse(json_string)
rescue JSON::ParserError => e
  puts "Failed to parse JSON: #{e.message}"
end

Output:


Failed to parse JSON: 767: unexpected token at '{"name":"John", "age":30'

10. Common Methods

MethodPurpose
JSON.generate(obj)Serialize Ruby object to JSON string.
JSON.pretty_generate(obj)Serialize Ruby object to pretty JSON string.
JSON.parse(json)Deserialize JSON string to Ruby object.
obj.to_jsonConvert Ruby object to JSON string.

Conclusion

As we saw many technologies here we come to end with some good and some bad parts about is so same also happening with the JSON.

It also have its advantages and disadvantage, like if you except a quick and perfect response from the server then you can refer it, it has the wide range of schema supported with that but to use that we the device should be on the trusted network otherwise meanwhile it can make a problem for yourself only.

Share this post

Comments (3)

  • Kenneth Kasajian Reply

    Recently after having drunk the JSON Kool-Aid, I needed to create a configuration file for one of our applications. This is the kind of thing I would ordinarily use an .ini file or .xml. Having never been a fan of XML (like ever!) I thought, JSON would be a great choice for configuration files. Considering the fact it’s used that way by many programming tools, I figure that sounds like a reasonable choice.

    Well, I regret that decision. This specific configuration file has many places where the user would have to type in a file path. Now they have to type two backslashes for every backslash. Try explaining that to an end-user. Even those who regularly edit the Windows registry will wtf @ that one. And before you think this is a Windows-only issue, it’s not just backslash. According to the JSON spec, the forward-slash character also must be escaped with a backslash. It’s bad enough that JSON requires keys to be quoted when they don’t need to be, but the escaping of strings is just an unnecessary complexity for users.

    I realize the JSON fan-boys will say that if it’s too complicated for the use, then you should create a UI. I’m really not buying that argument. I can’t believe I’m saying this, but XML would have been a better option.

    November 21, 2014 at 6:08 pm
  • Shawn Reply

    I’m not sure how the disadvantges are because of the json format? If you are saying that ajax calls cant return errors or handle errors you are not correct.

    November 21, 2014 at 6:20 pm
  • Kenneth Reply

    I don’t see the disadvantage really, basically the improper data handling is the problem and not an error. Try having zero fill or default and it will be gone.

    November 25, 2014 at 5:44 am

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Blog