Standard JSON parser that comes bundled with Java

2019-02-09 05:01发布

This question already has an answer here:

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.

2条回答
你好瞎i
2楼-- · 2019-02-09 05:31

There is the javax.script Api which is built in to 1.6 http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html

查看更多
【Aperson】
3楼-- · 2019-02-09 05:36

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);
};
查看更多
登录 后发表回答