How to parse JSON in Java

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567" 
        }
    ] 
}

JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON.

Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes.

Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model.

 

 

 

Write JSON to a file

Let us see an example that writes above JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray.

filter_none

edit

play_arrow

brightness_4

// Java program for write JSON to a file

  

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.LinkedHashMap;

import java.util.Map;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

  

public class JSONWriteExample

{

    public static void main(String[] args) throws FileNotFoundException 

    {

        // creating JSONObject

        JSONObject jo = new JSONObject();

          

        // putting data to JSONObject

        jo.put("firstName", "John");

        jo.put("lastName", "Smith");

        jo.put("age", 25);

          

        // for address data, first create LinkedHashMap

        Map m = new LinkedHashMap(4);

        m.put("streetAddress", "21 2nd Street");

        m.put("city", "New York");

        m.put("state", "NY");

        m.put("postalCode", 10021);

          

        // putting address to JSONObject

        jo.put("address", m);

          

        // for phone numbers, first create JSONArray 

        JSONArray ja = new JSONArray();

          

        m = new LinkedHashMap(2);

        m.put("type", "home");

        m.put("number", "212 555-1234");

          

        // adding map to list

        ja.add(m);

          

        m = new LinkedHashMap(2);

        m.put("type", "fax");

        m.put("number", "212 555-1234");

          

        // adding map to list

        ja.add(m);

          

        // putting phoneNumbers to JSONObject

        jo.put("phoneNumbers", ja);

          

        // writing JSON to file:"JSONExample.json" in cwd

        PrintWriter pw = new PrintWriter("JSONExample.json");

        pw.write(jo.toJSONString());

          

        pw.flush();

        pw.close();

    }

}

Output from file “JSONExample.json” :

{
     "lastName":"Smith",
    "address":{
        "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":10021
    },
     "age":25,
     "phoneNumbers":[
            {
            "type":"home", "number":"212 555-1234"
            },
         {
            "type":"fax", "number":"212 555-1234"
         }
     ],
     "firstName":"John"
}

Note : In JSON, An object is an unordered set of name/value pairs, so JSONObject doesn’t preserve the order of an object’s name/value pairs, since it is (by definition) not significant. Hence in our output file, order is not preserved.

Read JSON from a file

Let us see an example that read JSON data from above created file “JSONExample.json” with help of JSONParser, JSONObject and JSONArray.

filter_none

edit

play_arrow

brightness_4

// Java program to read JSON from a file

  

import java.io.FileReader;

import java.util.Iterator;

import java.util.Map;

  

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.*;

  

public class JSONReadExample 

{

    public static void main(String[] args) throws Exception 

    {

        // parsing file "JSONExample.json"

        Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));

          

        // typecasting obj to JSONObject

        JSONObject jo = (JSONObject) obj;

          

        // getting firstName and lastName

        String firstName = (String) jo.get("firstName");

        String lastName = (String) jo.get("lastName");

          

        System.out.println(firstName);

        System.out.println(lastName);

          

        // getting age

        long age = (long) jo.get("age");

        System.out.println(age);

          

        // getting address

        Map address = ((Map)jo.get("address"));

          

        // iterating address Map

        Iterator<Map.Entry> itr1 = address.entrySet().iterator();

        while (itr1.hasNext()) {

            Map.Entry pair = itr1.next();

            System.out.println(pair.getKey() + " : " + pair.getValue());

        }

          

        // getting phoneNumbers

        JSONArray ja = (JSONArray) jo.get("phoneNumbers");

          

        // iterating phoneNumbers

        Iterator itr2 = ja.iterator();

          

        while (itr2.hasNext()) 

        {

            itr1 = ((Map) itr2.next()).entrySet().iterator();

            while (itr1.hasNext()) {

                Map.Entry pair = itr1.next();

                System.out.println(pair.getKey() + " : " + pair.getValue());

            }

        }

    }

}

Output:

John
Smith
25
streetAddress : 21 2nd Street
postalCode : 10021
state : NY
city : New York
number : 212 555-1234
type : home
number : 212 555-1234
type : fax

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值