繁体   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