edu.birzeit.cs.parsers.TestParsingWithJSON.java Source code

Java tutorial

Introduction

Here is the source code for edu.birzeit.cs.parsers.TestParsingWithJSON.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.birzeit.cs.parsers;

/**
 *
 * @author nammar
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
//import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class TestParsingWithJSON {

    private static JSONTokener jsonOut;

    public static void main(String myHelpers[]) throws JSONException, IOException {

        File f = new File(
                "C:\\Users\\Bisan Co\\Documents\\NetBeansProjects\\WebApplication1\\src\\java/newjson.json");

        String jsonString = readFile(f.getPath());

        jsonOut = new JSONTokener(jsonString);
        JSONObject output = new JSONObject(jsonOut);

        String id = (String) output.getJSONObject("user1").get("-ID");
        System.out.println(id);

        String address = (String) output.getJSONObject("user2").getJSONObject("Friends").getJSONObject("friend1")
                .get("address");

        System.out.println(address);

    }

    private static String readFile(String file) throws IOException {

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        String ls = System.getProperty("line.separator");

        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    }

}