2012-08-06 69 views
1

我有多个JSON在一个文件input.txt中:多JSON解析Java中

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

注意:他们不是以逗号分隔(“”),他们是不是数组。这些是有效的单个JSON。

我相信应该有可能得到一个输出。

我的代码下面既不显示错误,也没有输出?这里有什么问题?

这是我的代码:

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

}} 
+0

在它看起来像你在错误的情况下打开每个记录乍看之下。 – 2012-08-06 16:46:24

回答

1

要传递的IOUtils.toString(BufferedReader)结果到JSONParser。如您所知,整个文件内容不是有效的JSON。假设每行都是有效的JSON,请将数据逐行传递给解析器。您的代码已经设置完成。

在您的循环中,将line传递给解析器,并删除IOUtils的东西。

我假定JSONParserorg.json.simple.parser.JSONParser。如果是这样,它将不会为您构建您的对象,而无需您做更多工作:它仅解析JSON并返回JSONObjects,JSONArray等的树。请参阅hereJSONAwarehere的位。

或者查看JacksonGSON以将您的JSON解析为java对象。

此外,您的Loc成员不能被命名为long:这是一个java关键字,并且会阻止您的代码编译。

+0

我在线程“main”中收到此错误异常java.lang.ClassCastException:org.json.simple.JSONObject无法转换为JsonSample.Employ \t at JsonSample.JsonReader.main(JsonReader.java:68) – labbyfrost 2012-08-06 06:15:17

2

你解析错误的东西。你应该解析line而不是jsonTextline是从BufferedReader中读入的实际行。

1

看起来你需要进行解析线,不jsonTxt

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