how to parse json in java

how to parse json in java

download the json jar
https://repo1.maven.org/maven2/org/json/json/
https://mvnrepository.com/artifact/org.json/json

jsontext

refe‮tual:ot r‬turi.com
{
    "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" 
        }
    ] 
}

parse json in java

/**
 * @author lautturi.com
 * Java example: parse json in java
 */

import java.util.*;

import org.json.JSONArray;
import org.json.JSONObject;

public class Lautturi {

	public static void main(String[] args) {

		String jsonString = "{\r\n" + 
				"    \"firstName\": \"John\",\r\n" + 
				"    \"lastName\": \"Smith\",\r\n" + 
				"    \"age\": 25,\r\n" + 
				"    \"address\": {\r\n" + 
				"        \"streetAddress\": \"21 2nd Street\",\r\n" + 
				"        \"city\": \"New York\",\r\n" + 
				"        \"state\": \"NY\",\r\n" + 
				"        \"postalCode\": 10021\r\n" + 
				"    },\r\n" + 
				"    \"phoneNumbers\": [\r\n" + 
				"        {\r\n" + 
				"            \"type\": \"home\",\r\n" + 
				"            \"number\": \"212 555-1234\"\r\n" + 
				"        },\r\n" + 
				"        {\r\n" + 
				"            \"type\": \"fax\",\r\n" + 
				"            \"number\": \"646 555-4567\" \r\n" + 
				"        }\r\n" + 
				"    ] \r\n" + 
				"}";
		JSONObject obj = new JSONObject(jsonString);
		
		String firstName = obj.getString("firstName");
		System.out.println(firstName);
		
		String city = obj.getJSONObject("address").getString("city");		
		System.out.println(city);
		
		JSONArray arr = obj.getJSONArray("phoneNumbers");
		for (int i = 0; i < arr.length(); i++)
		{
		    String number = arr.getJSONObject(i).getString("number");
		    System.out.println(number);
		    
		}
		

	}
}

output:

John
New York
212 555-1234
646 555-4567
Created Time:2017-09-12 21:01:05  Author:lautturi