0

In Spring mvc I have a mytable.json file.

I want to fetch that json file data and then want to add to model.addAttribute().

mytable.json

{"name1":["place1.1","place1.2"],
  "name2":["place2.1","place1.2"] 
...........
.........}

I want to fetch the names with their corresponding citylist.

Ex:

name1=place1.1,place1.2

so,I have done:--

     try {           

            JSONParser parser = new JSONParser();

             ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("file/mytable.json").getFile());
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));

            Iterator<String> keys = obj.values().iterator();

            while( keys.hasNext() ) 
            {
                String key = (String)keys.next();
                if ( obj.get(key) instanceof JSONObject )
                {
                    model.addAttribute("key", key);


                }

            }           


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

But I am getting error:

Unexpected character (�) at position 0.

in this line :

JSONObject obj = (JSONObject) parser.parse(new FileReader(file));

why??Where is the problem?

5
  • Can you check whether servletContext.getRealPath("/WEB-INF/mytable.json") get you the right path? Commented Dec 15, 2015 at 7:00
  • I have edited my question..and this is the right path.. Commented Dec 15, 2015 at 7:32
  • What JSON Parser are you using? I am able to parse with org.json.simple.parser.JSONParser Commented Dec 15, 2015 at 7:59
  • I am also using this Commented Dec 15, 2015 at 8:01
  • 1
    Can you just try recreating the file file/mytable.json? File encoding may have an issue here. Commented Dec 15, 2015 at 9:03

1 Answer 1

1

The JSONParser parser = new JSONParser(); is expecting a JSON String, not a .json file. hence the Unexpected character.... error.

You can InputStreamReader:

jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("file/mytable.json")));
Sign up to request clarification or add additional context in comments.

Comments

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.