使用 Java 读取多个对象 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25346512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:10:15  来源:igfitidea点击:

Read Multiple Objects JSON with Java

javajsongson

提问by Yuan

I need to read a JSON file in Java with the following structure:

我需要在 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"}

Thanks!.

谢谢!。



[POST-EDITED]

[后期编辑]

I have this code but only read the first JSON Object, I need read the three objects one by one.

我有这段代码,但只读取了第一个 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();
        }
    }

thanks!

谢谢!

回答by hurricane

I know two option for read JSON.

我知道读取 JSON 的两个选项。

JSON Simple its good for small JSON results. But GSON is very usefull for big json results. Because you can set Object form in GSON.

JSON Simple 它适用于小型 JSON 结果。但是 GSON 对于大的 json 结果非常有用。因为你可以在 GSON 中设置 Object 形式。

Firs one json.jar

第一个json.jar

Usage :

用法 :

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

Second One gson.jar

第二个gson.jar

Usage:

用法:

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

回答by prasadmadanayake

I think what you mean is your Json strings are stored in a text file and you need to read them in to a Json objects. If that's the case use BufferedReader or Scanner to read the file line by line and parse each line to a Json object using json-simple

我认为您的意思是您的 Json 字符串存储在一个文本文件中,您需要将它们读入 Json 对象。如果是这种情况,请使用 BufferedReader 或 Scanner 逐行读取文件,并使用json-simple 将每一行解析为 Json 对象

JsonReader is use to Read One Json Object. Use Scanner or BufferedReader to Read File Line By Line as String and then Parse it to a Json Object.Here is an Example

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

}

回答by Neill Lima

The proper way to work through this JSON file is:

处理此 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"
  }
]

Try using XStreamif you are using a standalone application. It parses JSON into objects in a blink of an eye.

如果您使用的是独立应用程序,请尝试使用XStream。它在眨眼间将 JSON 解析为对象。

回答by ojus kulkarni

My data format is :

我的数据格式是:

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

I tried this one and it works :

我试过这个,它有效:

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

回答by amitava

keep the data inside [ ] like [{"id_user":"10","level":"medium","text":"hello 10"} {"id_user":"20","level":"medium","text":"hello 20"} {"id_user":"30","level":"medium","text":"hello 30"}]

将数据保存在 [ ] 中,例如 [{"id_user":"10","level":"medium","text":"hello 10"} {"id_user":"20","level":"medium","text":"hello 20"} {"id_user":"30","level":"medium","text":"hello 30"}]

inside the file so that it becomes a list then you can use JSONArray . the way I wrote is as follows

在文件内部,使其成为一个列表,然后您可以使用 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();
    }
}

}

}

The output I get is

我得到的输出是

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

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

回答by halim

I know it has been almost one year for this post :) but i am actually reposing again as an answer because i had this problem same as you Yuan

我知道这篇文章已经快一年了 :) 但我实际上再次重新作为答案,因为我遇到了和你一样的问题 袁

I have this text.txt file - I know this is not a valid Json array - but if you look, you will see that each line of this file is a Json object in its case alone.

我有这个 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"}

Now I want to read each line of the above and parse the names "Sensor_ID" and "Date" into Json format. After long search, I have the following:

现在我想读取上面的每一行并将名称“Sensor_ID”和“Date”解析为 Json 格式。经过长时间的搜索,我有以下内容:

Try it and look on the console to see the result. I hope it helps.

试试看,在控制台上查看结果。我希望它有帮助。

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

回答by Victor

include following maven dependency:

包括以下 maven 依赖项:

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

then write your code as below:

然后编写您的代码如下:

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

回答by whaefelinger

This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrarysequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have formatted your input:

这是一个基于(并经过测试)的工作示例,使用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 */
       }

回答by Aditya

I used below code and its working fine.

我使用了下面的代码并且它工作正常。

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: {

JSON:{

"version": 1,

"dataLevels": 

[

{

  "name": "test1",

  "externId": "test1",

  "type": "test1"

},

{

  "name": "test2",

  "externId": "test2",

  "type": "test2"

},

{

  "name": "test3",

  "externId": "test3",

  "type": "test3"

}

]

]

}

}

回答by armagedescu

Using gson to read multiple objects from stream. With gson-2.8.2, I had to call this: reader.setLenient(true);

使用 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();

This was suggested explicitly by the stack trace, when I did it, the code worked perfectly:

这是堆栈跟踪明确建议的,当我这样做时,代码运行良好:

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)

...

...