从json文本文件加载JSONObject的最佳方法是什么?

Lar*_*rry 30 java json

将包含JSON的文件加载到JSONObject中的最简单方法是什么.

目前我正在使用json-lib.

这就是我所拥有的,但它抛出异常:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));
Run Code Online (Sandbox Code Playgroud)

输出是:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)
Run Code Online (Sandbox Code Playgroud)

jan*_*lle 32

谢谢@Kit Ho的回答.我使用了你的代码,发现我一直遇到错误,我的InputStream总是为null,而在创建JSONObject时则是ClassNotFound异常.这是我的代码版本,它为我提供了一些技巧:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

import org.json.JSONObject;
public class JSONParsing {
    public static void main(String[] args) throws Exception {
        File f = new File("file.json");
        if (f.exists()){
            InputStream is = new FileInputStream("file.json");
            String jsonTxt = IOUtils.toString(is, "UTF-8");
            System.out.println(jsonTxt);
            JSONObject json = new JSONObject(jsonTxt);       
            String a = json.getString("1000");
            System.out.println(a);   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现这个答案对于FileInputStream和getResourceAsStream之间区别很有启发性.希望这也有助于其他人.

  • 我不是Java开发人员,现在还没有时间去研究它,但你可能想看看[被拒绝的建议编辑到这篇文章](http://stackoverflow.com/review/suggested-edits/9220747)声称在这里修复你的代码中的竞争条件(据我所知,file.json可能会在`f.exists()`调用和从文件读取之间被删除,所以使用try/catch更好并考虑实施变革.另外:您的答案已在每日WTF论坛上提及:https://what.thedailywtf.com/t/sigh-why-do-i-even-try-a-novlet-on-stackoverflow/51280.恭喜? (5认同)
  • @janoulle是的,确切地说.出于这个原因,不是检查文件是否存在并继续使用它,如果确实如此,那么更好的做法是尝试使用该文件并处理`FileNotFoundException`(如果发生).当然,经常 - 甚至*通常* - 这在实践中根本不重要,因为你知道没有什么可以从脚下抢走文件,如果存在,或者因为你不关心你的程序在这种边缘情况下崩溃.但是,由于尝试/捕获方法没有任何缺点,我们也可以在这里展示最佳实践. (3认同)
  • @MarkAmery是的,这是一个经典[检查时间](https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use)错误.此外,"抛出异常"通常是主要的坏事. (2认同)
  • 不知何故,我错过了我评论中明显的编辑迷你战争。哈。感谢dailywtf 链接...相当可疑的成就。所以我可以理解我是如何搞砸的,正是这一行导致代码容易受到 TOCTOU 错误的影响: InputStream is = new FileInputStream("file.json") 重新打开文件,它可能已从我的初始 f.exists() 检查? (2认同)

Kit*_* Ho 23

试试这个:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是你的sample-json.txt,应该是json格式

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}
Run Code Online (Sandbox Code Playgroud)


IKo*_*IKo 9

使用java 8,您可以尝试这样:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}
Run Code Online (Sandbox Code Playgroud)