Reading multiple JSON objects with Java

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

{"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 I only read the first JSON object, I need to read three objects one by one.

 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!

+7
java json gson
source share
9 answers

I know that this post was almost one year old :), but I really am again as an answer, because I have the same problem as yours, Yuan

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

 {"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 above and parse the names "Sensor_ID" and "Date" in Json format. After a long search, I have the following:

Try it and look at the console to see the result. Hope this 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(); } } } 
+5
source share

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

  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 */ } 
+3
source share

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

JsonReader is used to read a single Json object. Use Scanner or BufferedReader to read a line of a file line by line as a line, and then parse it on a Json Object. Here is an example

 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; } } 
+2
source share

I know two options for reading JSON.

JSON Its simple use for small JSON results. But GSON is very useful for great json results. Because you can set the object form to GSON.

Firs one json.jar

Using:

 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 gson.jar

Using:

 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); 
0
source share

The correct way to work with this JSON file is:

 "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 XStream if you are using a standalone application. It parses JSON for objects in the blink of an eye.

0
source share

My data format:

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

save the data inside [] as [{"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. what i wrote is as follows

 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 name = new LinkedList(); LinkedList author = new LinkedList(); LinkedList company = new LinkedList(); for (int i =0; i< length; i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); Set s = jsonObject.entrySet(); Iterator iter = s.iterator(); LinkedList ll = new LinkedList(); LinkedList lm = new LinkedList(); while(iter.hasNext()){ Map.Entry me = (Map.Entry) iter.next(); //System.out.println(me.getKey() + " " + me.getValue()); ll.add(me.getValue()); lm.add(me.getKey()); } author.add(ll.get(0)); name.add(ll.get(1)); company.add(ll.get(2)); } System.out.println(name); System.out.println(author); System.out.println(company); } catch (Exception e) { e.printStackTrace(); } } 

}

The output I get is

[10, 20, 30] [medium, medium, medium] [hello 10, hello 20, hello 30]

if you uncomment "System.out.println (me.getKey () +" "+ me.getValue ());" you get the following output level medium id_user 10 text hello 10 level medium id_user 20 text hello 20 level medium id_user 30 text hello 30

I like the first one (three linked lists), these lists are ordered and can be easily edited / searched, I mean using the index, I can always find the corresponding items from other lists.

0
source share

include the following maven dependency:

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

}}

0
source share

I used the code below and its performance.

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

]

}

0
source share

All Articles