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

8
  • 1
    What output are you actually getting? Is it throwing an exception? If so post that in your question Commented Jan 12, 2015 at 4: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 Commented Jan 12, 2015 at 4: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. Commented Jan 12, 2015 at 4:56
  • 2
    I think you should have a look at this :stackoverflow.com/questions/10926353/… Commented Jan 12, 2015 at 4:57
  • possible duplicate of Parse JSON in JavaScript? Commented Jan 12, 2015 at 5:02

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Code does this help you
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.

Comments

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

Comments

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

6 Comments

@ 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.<init>(JSONObject.java:185) at org.json.JSONObject.<init>(JSONObject.java:402)
you need post text file contents you are trying to parse
@ Super Hornet I didn't get you .Please explain
I mean contents of 101.txt
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.