2

I am new to JSON and Java ,using following code ,I am trying to read JSON data from text file but its not showing result for multiple value data

Anyone Please help me ,Let me know where I am wrong

    JSONParser parser = new JSONParser();              
    try {  
     Object obj = parser.parse(new FileReader("C:/Users/Desktop/file.json"));  
     JSONObject jsonObject = (JSONObject) obj;  
     String K1= (String) jsonObject.get("V1");  
     String K2= (String) jsonObject.get("V2"); 



     System.out.println(V1);
      System.out.println(V2);

       JSONArray K3= (JSONArray) jsonObject.get("K3");

       for (Object c : K3)
       {
         System.out.println(c+"");

       }
 } catch ( Exception e){
                 e.printStackTrace();

 }  
}
}


File.json
{"K1":"V1" ,"K2":"V2" ,"K3" : "V3.1 ,V3.2"}

CURRENT Output : V1 V2

Expected output V1 V2 V3.1 V3.2

any pls tell me where I am wrong

Code
  • 57
  • 1
  • 9
  • 1
    What output are you actually getting? Is it throwing an exception? If so post that in your question – Alex Jan 12 '15 at 04:50
  • @Alex , Its not showing any exception ,its giving perfect answer but my concern is if instead of JSON String ,I want to read same data from JSON File then how it should be done here ,I am new to this so I got confused there I have Google it too but didn't got it – Code Jan 12 '15 at 04:55
  • A JSON IS effectively a `String` following the pattern you have already posted in your question. If you want to read it from a file use a `BufferedReader` or something to read it from a file and then do what you have already done with the `JSON_DATA` `String`. – shyam Jan 12 '15 at 04:56
  • 2
    I think you should have a look at this :http://stackoverflow.com/questions/10926353/how-to-read-json-file-into-java-with-simple-json-library – AppleBud Jan 12 '15 at 04:57
  • possible duplicate of [Parse JSON in JavaScript?](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Jayan Jan 12 '15 at 05:02
  • @Shyam Can you Please elaborate ,your explanation will help me lot. – Code Jan 12 '15 at 05:15
  • @Jayan I think you've picked the wrong dupe; this question is asking about how to parse it using java, not javascript. – Dennis Meng Jan 12 '15 at 06:13
  • @Dennis Meng: true! Thanks. Now I retracted my close vote. – Jayan Jan 12 '15 at 06:36

4 Answers4

0

Either you do manual parsing or you deserialize. I don't see both. For now, you can do manual parsing. Should be some like

JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj = parser.parse(s);
Asm
  • 26
  • 2
0

Use below example to read data from text file.

http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Instead of hard coded value for "JSON_DATA" variable in your code, use the value in "sCurrentLine" in above code segment.

0

Some lines should go inside while loop because when the loop is finished sCurrentLine is null. So there is nothing to be parsed and then NullPointerException would be thrown. Also each line should has this pattern: {"Key":"Value"}

public class Address {
  public static void main(String[] args) throws JSONException {
    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:/Users/Desktop/101.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
            final JSONObject obj = new JSONObject(sCurrentLine);
            final JSONArray geodata = obj.getJSONArray("geodata");
            final int n = geodata.length();
            for (int i = 0; i < n; ++i) {
              final JSONObject person = geodata.getJSONObject(i);
              System.out.println(person.getInt("id"));
              System.out.println(person.getString("name"));
              System.out.println(person.getString("gender"));
              System.out.println(person.getDouble("latitude"));
              System.out.println(person.getDouble("longitude"));
            }
        }     

     } catch (IOException e) {
         e.printStackTrace();
     } finally {
       try {
         if (br != null)br.close();
        } catch (IOException ex) {
         ex.printStackTrace();
        }
     }
}
}
Super Hornet
  • 2,839
  • 5
  • 27
  • 55
  • @ super hornet ,I have tried you code it showing following errorException in thread "main" org.json.JSONException: A JSONObject text must end with '}' at character 1 at org.json.JSONTokener.syntaxError(JSONTokener.java:410) at org.json.JSONObject.(JSONObject.java:185) at org.json.JSONObject.(JSONObject.java:402) – Code Jan 12 '15 at 06:34
  • you need post text file contents you are trying to parse – Super Hornet Jan 12 '15 at 06:42
  • @ Super Hornet I didn't get you .Please explain – Code Jan 12 '15 at 07:03
  • I mean contents of `101.txt` – Super Hornet Jan 12 '15 at 07:06
  • ok ,correct me if I am wrong then ,means I have to take content in string and then proceed right ? Can't we just read JSON file and print its individual element like " Id : 1" and so on – Code Jan 12 '15 at 07:09
  • As I mentioned in my answer, each line of text file should be like this: `{"key":"value"}` otherwise it can't be parsed as json object – Super Hornet Jan 12 '15 at 07:15
0

I find it better to parse JSON data in the object oriented way. And that means binding the data to Java Beans which can be very handy to do your work. First off let me say this will require a JAR namely gson.jar

  1. Define the GeoData class to represent geo data only

    public class GeoData {

            private String id;
            private String name;
            private String latitude;
            private String longitude;
            public String getId() {
                return id;
            }
            public void setId(String id) {
                this.id = id;
            }
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            public String getLatitude() {
                return latitude;
            }
            public void setLatitude(String latitude) {
                this.latitude = latitude;
            }
            public String getLongitude() {
                return longitude;
            }
            public void setLongitude(String longitude) {
                this.longitude = longitude;
            }
    
        }
    

Next build a wrapper, which holds a list of GeoData. To match your input. Please note that your input file has geodata key, with list of GeoData(the sample you provided)

public class GeoDataHolder {

    GeoData[] geodata;

    public GeoData[] getGeodata() {
        return geodata;
    }

    public void setGeodata(GeoData[] geodata) {
        this.geodata = geodata;
    }
}

Lastly here is an example of parsing the file:

public static void main(String[] args) throws FileNotFoundException {
        //read the file
        JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(new FileInputStream(new File("F:\\workspace\\Parser\\geodata.xml")))));
        Gson gson = new Gson();
        GeoDataHolder response = gson.fromJson(reader, GeoDataHolder.class);
        //geodataholder is the root element
        System.out.println("size: " + response.getGeodata().length);

        for(int i=0;i<response.getGeodata().length;i++){
            System.out.println("size: " + response.getGeodata()[i].getName());
        }
    }
ZakiMak
  • 2,072
  • 2
  • 17
  • 26