简体   繁体   中英

Spring MVC can not fetch JSON value

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?

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")));

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