简体   繁体   中英

Multiple JSON parsing in Java

I have multiple JSON in a single file input.txt:

{"Atlas":{"location":"lille","lat":28.4,"long":51.7,"country":"FR"}}
{"Atlas":{"location":"luxum","lat":24.1,"long":54.7,"country":"LU"}}
{"Atlas":{"location":"ghent","lat":28.1,"long":50.1,"country":"BE"}}

NOTE: they are not separated by comma (",") and they are not array. These are valid single JSON.

I believe it should be possible to get an output.

My code below neither shows an error nor gives an output? What is wrong here?

This is my code:

 class Loc{
        private String location;
        private Long lat;
        private Long long;
        private String country;

    //getter and setter methods
    }
    public class JsonReader {
        public static void main(String[] args) throws ParseException {

            try {
                BufferedReader br= new BufferedReader(new FileReader("C:\\input.txt"));
                String jsonTxt = IOUtils.toString( br );                
                JSONParser parser = new JSONParser();                               
                String line=null;
                while ((line = br.readLine()) != null)
                {
                    Loc emp = (Loc) (new JSONParser().parse(jsonTxt));
                    System.out.printf("%s",emp.getLocation());
                    System.out.printf("\t%d",emp.getlat());
                    System.out.printf("\t%d",emp.getLong());
                    System.out.printf("\t%s",emp.getCountry()"\n");
            }
    }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

}}

You're parsing the wrong thing. You should be parsing line not jsonText . line is the actual line read in from the BufferedReader.

You're passing the result of IOUtils.toString(BufferedReader) to the JSONParser . As you've noted, the entire file content isn't valid JSON. Assuming that each line is valid JSON, pass the data line-by-line to the parser. Your code is already set up to do this.

In your loop, pass line to the parser, and get rid of the IOUtils stuff.

I assume that JSONParser is org.json.simple.parser.JSONParser . If so, it won't build your Loc objects for you without more work on your part: it only parses the JSON and returns a tree of JSONObjects , JSONArray , etc. See here and the bit about JSONAware here .

Or look into Jackson or GSON for parsing your JSON into java objects.

Also, your Loc member can't be named long : that's a java keyword, and will prevent your code from compiling.

看起来你需要解析行,而不是jsonTxt

Loc emp = (Loc) (new JSONParser().parse(jsonTxt));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM