使用java读取包含JSON的文本文件

时间:2016-07-26 13:23:54

标签: java

我有一个txt文件。它包含所有json的。以下是样本数据.. {" userid":" 0be57386-b081-41fc-b5c4-98103956371f","细分":[" 2_GMC_L"]} {&# 34; userid":" 57f2f319-ed9b-4dc9-a550-70b51b724acb"," segments":[" 2_GMC_L"]} {" userid":" ba009949-f658-4abe-a707-d2b460ee2046","细分":[" 2_GMC_L"]} 我必须通过json获取整个数据json ..作为字符串值。并打印...

1 个答案:

答案 0 :(得分:0)

使用JSONParser类解析JSONString,找到下面的示例代码。

 JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader(
                    "/Users/Jiten/Documents/file1.txt"));

            JSONObject jsonObject = (JSONObject) obj;

            String name = (String) jsonObject.get("name");
            String author = (String) jsonObject.get("author");
            JSONArray companyList = (JSONArray) jsonObject.get("companyList");

            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();
        }