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

时间:2021-03-15 16:56:13

What would be the easiest way to load a file containing JSON into a JSONObject.

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

At the moment I am using json-lib.

目前我正在使用json-lib。

This is what I have, but it throws an exception:

这就是我所拥有的,但它抛出了一个例外:

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

The output is:

的输出是:

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)

4 个解决方案

#1


21  

try this:

试试这个:

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

and this is your sample-json.txt , should be in json format

这是你的样本-json。txt,应该是json格式

{'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':{'firstName':'Buzz',
          'lastName':'Aldrin'},
 'mission':'apollo 11'}

#2


27  

Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

感谢@Kit Ho的回答。我使用了您的代码,发现我一直在运行错误,在创建JSONObject时,我的InputStream总是null和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);   
        }
    }
}

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.

我发现这个答案对FileInputStream和getresourcesstream之间的区别很有启发。希望这也能帮助别人。

#3


4  

With java 8 you can try this:

使用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
    }
}

#4


1  

Another way of doing the same could be using the Gson Class

另一种方法是使用Gson类

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

这将提供解析要处理的json字符串后获得的对象。

#1


21  

try this:

试试这个:

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

and this is your sample-json.txt , should be in json format

这是你的样本-json。txt,应该是json格式

{'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':{'firstName':'Buzz',
          'lastName':'Aldrin'},
 'mission':'apollo 11'}

#2


27  

Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

感谢@Kit Ho的回答。我使用了您的代码,发现我一直在运行错误,在创建JSONObject时,我的InputStream总是null和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);   
        }
    }
}

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.

我发现这个答案对FileInputStream和getresourcesstream之间的区别很有启发。希望这也能帮助别人。

#3


4  

With java 8 you can try this:

使用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
    }
}

#4


1  

Another way of doing the same could be using the Gson Class

另一种方法是使用Gson类

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

这将提供解析要处理的json字符串后获得的对象。