Showing posts with label Java JSON. Show all posts
Showing posts with label Java JSON. Show all posts

JSON & Java — A Beginner-Friendly Guide

JSON & Java — A Beginner-Friendly Guide

Modern applications constantly exchange data between browsers, servers, and mobile apps. To make this communication simple and universal, we use a lightweight data format called JSON.

This blog explains:

  • What is JSON?

  • Why JSON is so popular

  • How JavaScript uses JSON

  • How Java interacts with JSON

  • How to create and read JSON objects (with examples)


1. What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging data.

It is:

  • Human readable

  • Language independent

  • Easy for machines to parse

  • Universally supported

✔ JSON represents data using:

  • Key–value pairs

  • Arrays

  • Nested objects

✔ JSON is widely used in:

  • REST APIs

  • Web applications

  • Mobile apps

  • Server-to-server communication

  • Configuration files


2. Why JSON Is So Popular

JSON became the standard for data exchange because:

FeatureWhy It Matters
LightweightSmaller size → faster communication
ReadableEasy for humans and developers
Language-freeWorks in JavaScript, Java, Python, Go, etc.
Native in JavaScriptPerfect for web browsers
Easy to parseSimple tools available in all languages

3. JSON in JavaScript

JSON was originally inspired by JavaScript object syntax.
In fact, JavaScript treats JSON almost like a native object.

Example:

var person = { "name": "Vinod", "address": "Bangalore", "designation": "Open source Publisher", "employer": "Self Business" };

Accessing values:

console.log(person.name); console.log(person.address);

4. JSON in Java

Java uses libraries to parse and create JSON because Java is strictly typed.

Popular Java libraries:

  • Jackson

  • Gson

  • JSON.simple

  • Org.JSON

Typical Java JSON operations:

➤ Convert JSON string → Java Object

➤ Convert Java Object → JSON string

➤ Read fields from JSON

➤ Create nested JSON structures

Example in Java using Jackson:

ObjectMapper mapper = new ObjectMapper(); String json = "{\"name\":\"Vinod\", \"address\":\"Bangalore\"}"; Person person = mapper.readValue(json, Person.class); System.out.println(person.getName());

5. JSON Connecting Java ↔ JavaScript

✔ Browser → Server → Browser flow

  1. JavaScript creates JSON

  2. Sends JSON to Java backend using REST API

  3. Java backend processes JSON

  4. Java sends JSON response back

  5. JavaScript reads JSON and updates UI

This is the core flow of all modern websites.


6. Creating JSON in JavaScript (Full Example)

Here is your example cleaned and formatted for blog readers:


📄 Example: Creating & Displaying a JSON Object in JavaScript

<html> <head> <title>Creating JSON Object</title> <script> // Creating a JSON object var jsonObject = { "address": "Bangalore", "designation": "Open source Publisher", "employer": "Self Business", "name": "Vinod" }; document.write("<h1>JSON Object Details</h1>"); document.write("<h3>Name: " + jsonObject.name + "</h3>"); document.write("<h3>Address: " + jsonObject.address + "</h3>"); document.write("<h3>Designation: " + jsonObject.designation + "</h3>"); document.write("<h3>Employer: " + jsonObject.employer + "</h3>"); </script> </head> <body> </body> </html>

Output

JSON Object Details Name: Vinod Address: Bangalore Designation: Open source Publisher Employer: Self Business

7. Convert JSON ↔ String in JavaScript

Convert object → JSON string:

var jsonStr = JSON.stringify(jsonObject); console.log(jsonStr);

Convert JSON string → object:

var obj = JSON.parse(jsonStr); console.log(obj.name);

8. Java + JSON Example

Java object to JSON:

ObjectMapper mapper = new ObjectMapper(); Person p = new Person("Vinod", "Bangalore"); String json = mapper.writeValueAsString(p); System.out.println(json);

JSON to Java object:

String json = "{\"name\":\"Vinod\"}"; Person p = mapper.readValue(json, Person.class);

9. Summary

JSON is the most popular format for data exchange because:

  • It is simple and readable

  • Works across all languages

  • JavaScript handles it naturally

  • Java has rich libraries to parse and generate JSON

Whether you're building a web application, mobile app, or backend system, JSON is at the heart of modern development.


FlexJSON API Examples

What is FlexJSON?

Flexjson is a lightweight java library for serializing and de-serializing java beans, maps, arrays and collections in JSON format.What's different about Flexjson is it's control over what gets serialized allowing both deep and shallow copies of objects.
You can download FlexJson jar from http://sourceforge.net/projects/flexjson/

In this example we can see

1. How to convert Java object to Json

2. How to convert List of object to Json

3. How to convert Map to Json

4. How to convert Json to Java object

5. How to use pretty print.

FlexJSON Serialization Example

1. Add below dependency in your pom.xml

<dependency>
            <groupId>net.sf.flexjson</groupId>
            <artifactId>flexjson</artifactId>
            <version>2.0</version>
        </dependency>

Below is one simple example to serialize Java Object Json String

2. Create a simple java pojo

 

package com.vinod.test;

public class Customer {
    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
    public Customer() {}
    private String name;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }
}
 

3. Create a Java class to do Flex Json operations

package com.vinod.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

public class FlexJsonExample {

    public static void main(String[] args) {

        // Java object to Json
        JSONSerializer serializer = new JSONSerializer();
        serializer.prettyPrint(true);
        Customer customer = new Customer("Vinod", "Bangalore");
        String flexJsonString = serializer.serialize(customer);
        System.out.println(flexJsonString);

        // Java Map key value pair to Json

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("NAME", "vinod");
        data.put("LOCATION", "Bangalore");
        data.put("ADDRESS", customer);
        String mapstring = serializer.serialize(data);
        System.out.println(mapstring);

        // Java list of object to Json String
        Customer customer1 = new Customer("Vinod", "Bangalore");
        Customer customer2 = new Customer("Raghava", "Bangalore");
        Customer customer3 = new Customer("Krishna", "Bangalore");

        List<Customer> pcs = Arrays.asList(customer1, customer2, customer3);
        String listString = serializer.serialize(pcs);
        System.out.println(listString);

        // Deserialization

        Customer custo = (Customer) new JSONDeserializer().use(null, Customer.class).deserialize(flexJsonString);
        System.out.println(custo);

    }

}
  

4. Output

{
    "address": "Bangalore",
    "class": "com.vinod.test.Customer",
    "name": "Vinod"
}
{
    "LOCATION": "Bangalore",
    "ADDRESS": {
        "address": "Bangalore",
        "class": "com.vinod.test.Customer",
        "name": "Vinod"
    },
    "NAME": "vinod"
}
[
    {
        "address": "Bangalore",
        "class": "com.vinod.test.Customer",
        "name": "Vinod"
    },
    {
        "address": "Bangalore",
        "class": "com.vinod.test.Customer",
        "name": "Raghava"
    },
    {
        "address": "Bangalore",
        "class": "com.vinod.test.Customer",
        "name": "Krishna"
    }
]
Customer [name=Vinod, address=Bangalore]
 

5. Done!!.. Download example

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-java-mapping

Reference

http://flexjson.sourceforge.net/

 

 

Gson API : Java object -> Json and Json -> Java object Example

JSON
JavaScript Object Notation is a popular alternative for xml and it is very simple and easy to read and write data exchange format. There are lot of third party libraries are available to processing JSON data like JSON.simple,Jackson,Gson etc

Gson
Gson is a Open sources API from Google to convert Java object to JSON representation and JSON to Java Object. The source code is available in Google site (http://code.google.com/p/google-gson)

Example:

Create a Maven Project and add below dependencies

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

Note: After maven clean make sure that gson jars are added in the dependencies.

Create a POJO class

package com.vinod.test;

public class Customer {
    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
    public Customer() {}
    private String name;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }
}
 

Create a Test class

package com.vinod.test;

import com.google.gson.Gson;

public class GsonExample {

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

        // convert java object to JSON format,
        Customer customer = new Customer("vinod", "Bangalore");
        String customerJson = gson.toJson(customer);
        System.out.println(customer);
        // convert json to java object
        Customer cust = gson.fromJson(customerJson, Customer.class);
        System.out.println(cust);

    }
}
 

Output

Customer [name=vinod, address=Bangalore]

Customer [name=vinod, address=Bangalore]

 

Done!!!


Json parsing using Simple Json API

JSON.Simple Example

JSON.simple is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text.

Mapping between Java and Json entities

JSON
Java
string
java.lang.String
number
java.lang.Number
true|false
java.lang.Boolean
null
null
array
java.util.List
object
java.util.Map
Create a maven project and add below dependencies
 
<dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
 
Create a json file  (jsontest.json)
 

{"age":25,"name":"vinod","phonenumbers":["999999999","888888888","77777777"]}


Create a test class

package com.vinod.test;

import java.io.FileReader;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class SimpleJsonTest {

    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try {
               // use parser
              Object obj = parser.parse(new FileReader("jsontest.json"));
               // converting
               JSONObject jsonObject = (JSONObject) obj;
               String name = (String) jsonObject.get("name");
               System.out.println(name);
               long age = (Long) jsonObject.get("age");
               System.out.println(age);
               // loop array
               JSONArray msg = (JSONArray) jsonObject.get("phonenumbers");
               Iterator<String> iterator = msg.iterator();
               while (iterator.hasNext()) {
                     System.out.println(iterator.next());
               }

        } catch (Exception e) {

               e.printStackTrace();

        }
    }

}
 

Output

vinod

25

999999999

888888888

77777777


 

Jackson API : Java Object to Json and Json to Java

JSON
JSON (JavaScript Object Notation) is a popular alternative for xml and it is very simple and easy to read and write data exchange format. There are lot of third party libraries are available to processing JSON data like JSON.simple,Jackson,Gson etc.
Here is one example how Jackson is convert a java object in to JSON and JSON to Java Object.

Create a Maven Project and add below dependencies

<repositories>
        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.5</version>
        </dependency>
    </dependencies>

Note: After maven clean make sure that jackson-mapper and jackson-core jars are added in the dependencies.

Test class

package com.vinod.test;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

public class ObjectToJson {
    public static void main(String[] args) {
        Customer customer = new Customer("vinod", "bangalore");
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        try {
            // Object to JSON String
            String customerJson = ow.writeValueAsString(customer);
            System.out.println(customerJson);

            // Json String to object
            ObjectMapper mapper = new ObjectMapper();

            Customer cus = mapper.readValue(customerJson, Customer.class);
            System.out.println(cus);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Customer {
    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
    public Customer() {}
    private String name;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }

}

Output

{

  "address" : "bangalore",

  "name" : "vinod"

}

Customer [name=vinod, address=bangalore]

 

 


Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts