繁体   English   中英

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

[英]What’s the best way to load a JSONObject from a json text file?

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

目前我正在使用 json-lib。

这就是我所拥有的,但它引发了一个异常:

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

输出是:

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)

感谢@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);   
        }
    }
}

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

试试这个:

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

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

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

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

另一种方法是使用 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);

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

Google'e Gson库中,有一个JsonObject或更抽象的JsonElement

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );

这不需要给定的对象结构来接收/读取 json 字符串。

2021 年 5 月 13 日编辑:正如我自己评论的那样:此解决方案无法正确处理关闭流!
这样做:

JsonElement json = null;
try (Reader reader = new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8")) {
    json = JsonParser.parseReader( reader );
} catch (Exception e) {
    // do something
}

正如人们所见,代码在正确执行时会变得臃肿。 我会清理代码将“从文件加载 json”移动到 FileUtils.class 中; 它可能已经存在并且做了超级好的可调整异常处理......

我正在使用的 json 示例:

"identity" : {
  "presentProvince" : [ {
    "language" : "eng",
    "value" : "China"
  } ],
  "presentAddressLine1" : [ {
    "language" : "eng",
    "value" : "bjbjbhjbhj"
  } ],
 "permanentAddressLine4" : [ {
    "language" : "eng",
    "value" : "123456"
  } ]
} } 

这是访问语言和值的代码:

public static void JsonObjParsing() throws Exception {
    File f = new File("id.json");
    if (f.exists()){
        InputStream is = new FileInputStream(f);
        String jsonTxt = IOUtils.toString(is, "UTF-8");
        System.out.println(jsonTxt);
            
            
        JSONObject json = new JSONObject(jsonTxt); 
           
        JSONObject identity = json.getJSONObject("identity");
            
            
        JSONArray identityitems = identity.getJSONArray("presentProvince");
        for (Object o : identityitems) {
            JSONObject jsonLineItem = (JSONObject) o;
            String language = jsonLineItem.getString("language");
            String value = jsonLineItem.getString("value");
            System.out.println(language +" " + value);
        }
    } 
}


public static void main(String[] args) throws Exception {
    JsonObjParsing();
}

在文件中获取 json 数组或仅获取 json 的一种方法是

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);

List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);

file.json 需要放在资源文件夹中。 如果您的文件只有一个没有 json 数组方括号 [] 的 json 块,您可以跳过 CollectionType

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);

另请参阅此处以获取我绘制的原始答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM