Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard JSON parser that comes bundled with Java [duplicate]

Tags:

java

json

parsing

I need to be able to read a JSON string from a file and parse it.

I want to know if the string is a "well formed" JSON. If so, I need to be able to read all the name value pairs.

Is there a JSON library that comes bundled with Java itself?

I would prefer something that comes with the standard Java distribution instead of downloading another external library.

I am using JDK 1.6.

like image 895
davison Avatar asked Sep 29 '14 17:09

davison


1 Answers

Try it approach without using external library

http://blog.julienviet.com/2011/12/26/json-to-java-with-jdk6/

EDITED

GitHub is more reliable source of the code from specified link. https://gist.github.com/vietj/1521692

The key is to use javascript to parse, it can be invoked with:

public class JSON2Java {

   private static final ScriptEngine jsonParser;

   static
   {
      try
      {
         String init = read(Tools.class.getResource("json2java.js"));
         ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
         engine.eval(init);
         jsonParser = engine;
      }
      catch (Exception e)
      {
         // Unexpected
         throw new AssertionError(e);
      }
   }

   public static Object parseJSON(String json)
   {
      try
      {
         String eval = "new java.util.concurrent.atomic.AtomicReference(toJava((" + json + ")))";
         AtomicReference ret = (AtomicReference)jsonParser.eval(eval);
         return ret.get();
      }
      catch (ScriptException e)
      {
         throw new RuntimeException("Invalid json", e);
      }
   }
}

Javascript part, json2java.js:

toJava = function(o) {
  return o == null ? null : o.toJava();
};
Object.prototype.toJava = function() {
  var m = new java.util.HashMap();
  for (var key in this)
    if (this.hasOwnProperty(key))
      m.put(key, toJava(this[key]));
  return m;
};
Array.prototype.toJava = function() {
  var l = this.length;
  var a = new java.lang.reflect.Array.newInstance(java.lang.Object, l);
  for (var i = 0;i < l;i++)
    a[i] = toJava(this[i]);
  return a;
};
String.prototype.toJava = function() {
  return new java.lang.String(this);
};
Boolean.prototype.toJava = function() {
  return java.lang.Boolean.valueOf(this);
};
Number.prototype.toJava = function() {
  return java.lang.Integer(this);
};
like image 195
kemenov Avatar answered Oct 31 '22 16:10

kemenov