簡體   English   中英

解析JSON對象文件並轉換為JSON數組

[英]Parse a file of JSON objects and convert to JSON array

我有一個包含JSON對象的文件。 我正在嘗試在Java程序中使用其URL訪問文件,以按如下方式訪問其內容。

URL url = new URL(Url);
URLConnection request = url.openConnection();
request.connect();
JsonReader jr = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
jr.setLenient(true);
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(jr);

我必須使用jr.setLenient(true); 因為數據不是JSON對象,而是多個JSON對象。 但是這種方法並不能幫助我獲取文件中的所有JSON對象。 我正在嘗試獲取所有JSON對象,遍歷每個對象,然后將數據保存到我的數據庫中。

我有以下URL接收到的數據類型的樣本: 樣本文件

有什么方法可以獲取文件中的所有對象以執行所需的操作。

另外,如果沒有任何效果,我可以手動將數據手動保存到新文件中的JSON數組中,但是每個JSON對象之間沒有逗號分隔,這使我很難解析數據。

但是每個JSON對象都是換行符。 因此,有什么方法可以基於此進行解析。

@marekful的建議是修復JSON字符串以獲得有效的字符串

public static void main(String[] args) throws Exception {
    URL url = new URL("http://d1kv7s9g8y3npv.cloudfront.net/testsite/files/doc-lib/2018/05/15/10/21/48/448/head/test3.txt#");
    URLConnection request = url.openConnection();
    request.connect();
    final Object content = request.getContent();

    BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content));
    String inputLine;

    List<String> jsonEntries = new ArrayList<>();
    while ((inputLine = br.readLine()) != null) {
        jsonEntries.add(inputLine);
    }
    String jsonString = "["  + jsonEntries.stream().collect(Collectors.joining(",")) +"]";

    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(jsonString);
    System.out.println(root);
}

}

我找到了一個對我來說很好的解決方案

URL url = new URL(urlString.trim());
URLConnection request = url.openConnection();
request.connect();
BufferedReader in = new BufferedReader(
        new InputStreamReader(
                request.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
{
    jsonObject = new JSONObject(inputLine);
    jsonArray.put(jsonObject);
}
in.close();

我能夠使用上述方法創建JSON數組,然后對該數組進行迭代以根據我的要求保存數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM