使用Java读取多个对象JSON

时间:2014-08-17 05:19:28

标签: java json gson

我需要使用以下结构读取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"}

谢谢!


[POST-EDITED]

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

谢谢!

10 个答案:

答案 0 :(得分:6)

我知道这个帖子已经差不多一年了:)但我实际上再次作为答案重新发布,因为我有这个问题和袁一样

我有这个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();
    }
}
}

答案 1 :(得分:3)

这是一个基于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 */
       }

答案 2 :(得分:2)

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

JsonReader用于读取一个Json对象。使用Scanner或BufferedReader逐行读取文件作为字符串,然后将其解析为Json Object.Here是一个示例

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

}

答案 3 :(得分:1)

包括以下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);
    }
}
}

答案 4 :(得分:0)

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

JSON简单,它适用于小型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);

答案 5 :(得分:0)

通过此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解析为对象。

答案 6 :(得分:0)

我的数据格式为:

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

答案 7 :(得分:0)

将数据保存在[]中 [{"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

答案 8 :(得分:0)

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

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"

}

}

答案 9 :(得分:0)

使用gson从流中读取多个对象。 使用gson-2.8.2,我不得不称之为:reader.setLenient(true);

JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.setLenient(true);
while (true)
{
    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)

...