簡體   English   中英

使用 Java 讀取多個對象 JSON

[英]Read Multiple Objects JSON with Java

我需要在 Java 中讀取具有以下結構的 JSON 文件:

{"id_user":"10","level":"medium","text":"hello 10"}
{"id_user":"20","level":"medium","text":"hello 20"}
{"id_user":"30","level":"medium","text":"hello 30"}

謝謝!。


[后期編輯]

我有這段代碼,但只讀取了第一個 JSON 對象,我需要一個一個讀取三個對象。

private void loadJSONFile(){
        FileReader fileReader = new FileReader(pathFile);
        try (JsonReader jsonReader = new JsonReader(fileReader)) {
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if (name.equals("filter_level")) {
                    System.out.println(jsonReader.nextString());
                } else if (name.equals("text")) {
                    System.out.println("text: " + jsonReader.nextString());
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
            jsonReader.close();
        }
    }

謝謝!

這是一個基於(並經過測試)的工作示例,使用gson-2.8.0 它接受給定輸入流上的任意JSON 對象序列。 而且,當然,它不會對您格式化輸入的方式施加任何限制:

       InputStream is = /* whatever */
       Reader r = new InputStreamReader(is, "UTF-8");
       Gson gson = new GsonBuilder().create();
       JsonStreamParser p = new JsonStreamParser(r);

       while (p.hasNext()) {
          JsonElement e = p.next();
          if (e.isJsonObject()) {
              Map m = gson.fromJson(e, Map.class);
              /* do something useful with JSON object .. */
          }
          /* handle other JSON data structures */
       }

我知道這篇文章已經快一年了 :) 但我實際上再次重新作為答案,因為我遇到了和你一樣的問題 袁

我有這個 text.txt 文件——我知道這不是一個有效的 Json 數組——但是如果你看一下,你會發現這個文件的每一行都是一個 Json 對象。

{"Sensor_ID":"874233","Date":"Apr 29,2016 08:49:58 Info Log1"}
{"Sensor_ID":"34234","Date":"Apr 29,2016 08:49:58 Info Log12"}
{"Sensor_ID":"56785","Date":"Apr 29,2016 08:49:58 Info Log13"}
{"Sensor_ID":"235657","Date":"Apr 29,2016 08:49:58 Info Log14"}
{"Sensor_ID":"568678","Date":"Apr 29,2016 08:49:58 Info Log15"}

現在我想讀取上面的每一行並將名稱“Sensor_ID”和“Date”解析為 Json 格式。 經過長時間的搜索,我有以下內容:

試試看,在控制台上查看結果。 我希望它有幫助。

package reading_file;

import java.io.*;
import java.util.ArrayList;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class file_read {
public static void main(String [] args) {
    ArrayList<JSONObject> json=new ArrayList<JSONObject>();
    JSONObject obj;
    // The name of the file to open.
    String fileName = "C:\\Users\\aawad\\workspace\\kura_juno\\data_logger\\log\\Apr_28_2016\\test.txt ";

    // This will reference one line at a time
    String line = null;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            obj = (JSONObject) new JSONParser().parse(line);
            json.add(obj);
            System.out.println((String)obj.get("Sensor_ID")+":"+
                               (String)obj.get("Date"));
        }
        // Always close files.
        bufferedReader.close();         
    }
    catch(FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

我認為您的意思是您的 Json 字符串存儲在一個文本文件中,您需要將它們讀入 Json 對象。 如果是這種情況,請使用 BufferedReader 或 Scanner 逐行讀取文件,並使用json-simple 將每一行解析為 Json 對象

JsonReader 用於讀取一個 Json 對象。 使用 Scanner 或 BufferedReader 逐行讀取文件作為字符串,然后將其解析為 Json 對象。這是一個示例

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class JSONExample{
public static void main(String x[]){
    String FileName="C:\\Users\\Prasad\\Desktop\\JSONExample.txt";
    try {
        ArrayList<JSONObject> jsons=ReadJSON(new File(FileName),"UTF-8");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
public static synchronized ArrayList<JSONObject> ReadJSON(File MyFile,String Encoding) throws FileNotFoundException, ParseException {
    Scanner scn=new Scanner(MyFile,Encoding);
    ArrayList<JSONObject> json=new ArrayList<JSONObject>();
//Reading and Parsing Strings to Json
    while(scn.hasNext()){
        JSONObject obj= (JSONObject) new JSONParser().parse(scn.nextLine());
        json.add(obj);
    }
//Here Printing Json Objects
    for(JSONObject obj : json){
        System.out.println((String)obj.get("id_user")+" : "+(String)obj.get("level")+" : "+(String)obj.get("text"));
    }
    return json;
}

}

包括以下 maven 依賴項:

   <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>

然后編寫您的代碼如下:

public class HistoricalData {
    private static final String PATH = "<PATH>";
    public static void main(String[] args) throws FileNotFoundException,

 ParseException {

    Scanner scanner = new Scanner(new File(PATH + "/Sample.txt"));
    List<JSONObject> jsonArray = new ArrayList<JSONObject>();
    while (scanner.hasNext()) {
        JSONObject obj = (JSONObject) new JSONParser().parse(scanner.nextLine());
        jsonArray.add(obj);
    }
}
}

將數據保存在 [ ] 中,如[{"id_user":"10","level":"medium","text":"hello 10"} {"id_user":"20","level":"medium","text":"hello 20"} {"id_user":"30","level":"medium","text":"hello 30"}]

在文件內部,使其成為一個列表,然后您可以使用 JSONArray 。 我寫的方式如下

public class JSONReadFromFile {

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("\\D:\\JSON\\file3.txt"));
        JSONArray jsonArray = (JSONArray) obj;
        int length = jsonArray.size();

        LinkedList author = new LinkedList();


        for (int i =0; i< length; i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Set s = jsonObject.entrySet();
            Iterator iter = s.iterator();

            HashMap hm = new HashMap();

            while(iter.hasNext()){
                Map.Entry me = (Map.Entry) iter.next();
                hm.put(me.getKey(), me.getValue());
            }
            author.add(hm);             
            }            
        for(int i=0;i<author.size();i++){
       HashMap hm = (HashMap) author.get(i);
       Set s = hm.entrySet();
       Iterator iter = s.iterator();
       while(iter.hasNext()){
           Map.Entry me = (Map.Entry) iter.next();
          System.out.println(me.getKey() + "---" + me.getValue());
          }   

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

我得到的輸出是

text---hello 10 id_user---10 level---medium text---hello 20 id_user---20 level---medium text---hello 30 id_user---30 level---medium

我知道讀取 JSON 的兩個選項。

JSON Simple 它適用於小型 JSON 結果。 但是 GSON 對於大的 json 結果非常有用。 因為你可以在 GSON 中設置 Object 形式。

第一個json.jar

用法 :

String st = ""; // your json object to string
JSONObject newJson = null;
    try {
        newJson = new JSONObject(st);
        newJson.getJSONObject("key");
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

第二個gson.jar

用法:

int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class);

處理此 JSON 文件的正確方法是:

"users": [
  {
    "id_user": "10",
    "level": "medium",
    "text": "hello 10"
  },
  {
    "id_user": "20",
    "level": "medium",
    "text": "hello 20"
  },
  {
    "id_user": "30",
    "level": "medium",
    "text": "hello 30"
  }
]

如果您使用的是獨立應用程序,請嘗試使用XStream 它在眨眼間將 JSON 解析為對象。

我使用了下面的代碼並且它工作正常。

public static void main(String[] args)
        throws IOException, JSchException, SftpException, InterruptedException, ParseException
{
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader("c:\\netapp1.txt"));
    Map<Object, Object> shareList = new HashMap<Object, Object>();
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray array = (JSONArray) jsonObject.get("dataLevels"); // it should be any array name

    Iterator<Object> iterator = array.iterator();
    while (iterator.hasNext())
    {
        Object it = iterator.next();
        JSONObject data = (JSONObject) it;
        shareList.put(data.get("name"), data.get("type"));
    }
    Iterator it = shareList.entrySet().iterator();
    while (it.hasNext())
    {
        Map.Entry value = (Map.Entry) it.next();
        System.out.println("Name: " + value.getKey() + " and type: " + value.getValue());
    }
}

JSON:{

"version": 1,

"dataLevels": 

[

{

  "name": "test1",

  "externId": "test1",

  "type": "test1"

},

{

  "name": "test2",

  "externId": "test2",

  "type": "test2"

},

{

  "name": "test3",

  "externId": "test3",

  "type": "test3"

}

]

}

使用 gson 從流中讀取多個對象。 使用 gson-2.8.2,我不得不調用它:reader.setLenient(true);

JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.setLenient(true);
while ((is.available() > 0))
{
    reader.beginObject();
    while (reader.hasNext()) {
        System.out.println("message: "+reader.nextName()+"="+reader.nextString());
    }
    System.out.println("=== End message ===");
    reader.endObject();

這是堆棧跟蹤明確建議的,當我這樣做時,代碼運行良好:

com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 3481 path $
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
    at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1409)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:542)
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:379)

...

我的數據格式是:

"array": [
  {
    "id": "1",
    "name": "peter",
    "text": "hie peter"
  },
  {
    "id": "5",
    "name": "rina",
    "text": "hey rina"
  },
  {
    "id": "12",
    "name": "parx",
    "text": "hey bro"
  }
]

我試過這個,它有效:

Object obj = parser.parse(new FileReader("/home/hp2/json.json"));

  JSONObject jsonObject = (JSONObject) obj;
  JSONArray array = (JSONArray) jsonObject.get("array"); // it should be any array name

     Iterator<Object> iterator = array.iterator();
        while (iterator.hasNext()) {
            System.out.println("if iterator have next element " + iterator.next());
        }

暫無
暫無

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

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