In this example I’ll use the same file which we have generated in previous tutorial.

Maven Dependency:

 

 
 
 
1
2
3
4
5
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

 

Previous Tutorial: http://crunchify.com/how-to-write-json-object-to-file-in-java/

 

CrunchifyJSONReadFromFile.java
 
 
Java
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.crunchify.tutorials;
 
import java.io.FileReader;
import java.util.Iterator;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
 
/**
* @author Crunchify.com
*/
 
public class CrunchifyJSONReadFromFile {
 
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
 
        try {
 
            Object obj = parser.parse(new FileReader(
                    "/Users/<username>/Documents/file1.txt"));
 
            JSONObject jsonObject = (JSONObject) obj;
 
            String name = (String) jsonObject.get("Name");
            String author = (String) jsonObject.get("Author");
            JSONArray companyList = (JSONArray) jsonObject.get("Company List");
 
            System.out.println("Name: " + name);
            System.out.println("Author: " + author);
            System.out.println("\nCompany List:");
            Iterator<String> iterator = companyList.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

Other must read: Create and Deploy simple Web Service and Web Service Client in Eclipse

Output:

 

 
 
 
1
2
3
4
5
6
7
Name: Crunchify.com
Author: App Shah
 
Company List:
Compnay: eBay
Compnay: Paypal
Compnay: Google

 

Download json-simple-1.1.1.jar

If you enjoyed this post, make sure to subscribe to Crunchify's RSS feed.
 
http://crunchify.com/how-to-read-json-object-from-file-in-java/
文章標籤
全站熱搜
創作者介紹
創作者 pcwiki 的頭像
pcwiki

pcwiki的部落格

pcwiki 發表在 痞客邦 留言(0) 人氣(1,425)