Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Multiple Objects JSON with Java

Tags:

java

json

gson

I need to read a JSON file in Java 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 only read the first JSON Object, I need read the 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!

like image 863
Yuan Avatar asked Aug 17 '14 05:08

Yuan


2 Answers

This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrary sequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have 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 */
       }
like image 147
wh81752 Avatar answered Sep 18 '22 13:09

wh81752


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

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

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

}
like image 25
prasadmadanayake Avatar answered Sep 21 '22 13:09

prasadmadanayake