3

My JSON file's content is :

{
"MJ" : "Michael Jordan",
"KB" : "Kobe Bryant",
"KG" : "Kevin Garnet"
}

Now it is easy to convert this file (or string) to a Java class (e.g: java.util.HashMap) if I use Gson or Jackson or JsonSimple or another Java/JSON third-party library. E.g., I can use Gson like this:

//this returns the string above
String jsonString = TestReader.getStrFromJSonFile();
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
HashMap<String, String> map = gson.fromJson(jsonString, type);

But,if my JSON file contains comments, most of the third-party libraries will not work. e.g.:

  {   
       //Bulls   
       "MJ" : "Michael Jordan",   
       /*Lakers*/  
       "KB" : "Kobe Bryant",    
       //Boston Celtics    
       "KG" : "Kevin Garnet"    
   }

Now I'm even confused after googling and stackoverflowing a lot. I have two questions:

  1. Can a JSON file really contain any comments? I think it can because I see a lot of this in JSON files everyday. But >>> (links)

  2. If it can, how can I solve my problem?

Community
  • 1
  • 1
Sam Su
  • 6,532
  • 8
  • 39
  • 80
  • 2
    Jackson supports comments if you enable that feature on the parser you use: http://jackson.codehaus.org/1.8.8/javadoc/org/codehaus/jackson/JsonParser.Feature.html – cmbaxter May 09 '13 at 17:23
  • possible duplicate of [Can I comment a JSON file?](http://stackoverflow.com/questions/244777/can-i-comment-a-json-file) – wchargin May 09 '13 at 17:42
  • @WChargin In fact,that's just one of my question,and my key point is the second question. – Sam Su May 09 '13 at 17:47
  • 1
    Comments like that do not comprise [legal JSON](http://www.json.org/), so you must use a JSON parser that is specifically enabled to handle them. No web service or other "generalized" source of JSON should produce comments that way. (Basically what you really have is JavaScript, not JSON.) – Hot Licks May 09 '13 at 19:03

1 Answers1

4

Jackson supports comments if you enable that feature on the parser you use:

https://fasterxml.github.io/jackson-core/javadoc/2.10/com/fasterxml/jackson/core/JsonParser.Feature.html

Per Lundberg
  • 3,837
  • 1
  • 36
  • 46
cmbaxter
  • 35,283
  • 4
  • 86
  • 95